Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Type-safe Programming Practice in Swift

Hank Bao
December 20, 2015

Type-safe Programming Practice in Swift

Swift 类型安全编程实践
2015年12月20日在 SwiftCon AlphaShow 沙龙上的分享

Hank Bao

December 20, 2015
Tweet

More Decks by Hank Bao

Other Decks in Programming

Transcript

  1. ᖫᦲ࢏༄ၥ extension UIImage { enum Asset: String { case Favorite

    = "favorite" case Project = "project" ... } convenience init(asset: Asset) { ... } } let img = UIImage(asset: .Project) @hankbao 9
  2. DataSource struct User { let id: String let name: String

    } struct Channel { let id: String let title: String } @hankbao 12
  3. DataSource class DataSource<Item>: NSObject, UITableViewDataSource { typealias Configure = (cell:

    UITableViewCell, item: Item) -> UITableViewCell } tableView.dataSource = DataSource<?>(configure: ...) @hankbao 13
  4. DataSource protocol ReuseIdentifierType { var reuseID: String { get }

    } extension DataItem: ReuseIdentifierType { var reuseID: String { switch self { case .UserItem: return "user_cell" case .ChannelItem: return "channel_cell" } } } @hankbao 15
  5. DataSource class DataSource<Item: ReuseIdentifierType>: NSObject, UITableViewDataSource { func tableView(tableView: UITableView,

    cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let item = items[indexPath.row] let cell = tableView.dequeueReusableCellWithIdentifier(item.reuseID, forIndexPath: indexPath) return configure(cell: cell, item: item) } ... } @hankbao 16