测试已测试 | ✓ |
语言语言 | SwiftSwift |
许可证 | BSD 3.0 |
发布最新版本 | 2017年1月 |
SwiftSwift 版本 | 3.0 |
SPM支持 SPM | ✗ |
由 Oleksa Korin 维护。
IDPCastable是一种可链式转换类型,用于在工作与单个变量下的多个不相关类型时,避免过度使用iflets和guards。
您可以在以下博客文章中了解更多有关转换及其如何帮助您简化代码的信息:类型推断,链式转换
一个完美的例子是,在UITableView中展示不同类型的cells,而没有共同的协议。通常编写的代码如下
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let identifier = (indexPath.row % 2) == 0 ? "GrayCell" : "PinkCell"
let cell = tableView.dequeueReusableCell(withIdentifier: identifier, for: indexPath)
if let pinkCell = cell as? PinkCell {
pinkCell.fill(withModel: indexPath.row)
}
if let grayCell = cell as? GrayCell {
grayCell.fill(withModel: "row = \(indexPath.row), column = \(indexPath.section)")
}
return cell
}
IDPCastable的使用代码
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let identifier = (indexPath.row % 2) == 0 ? "GrayCell" : "PinkCell"
let cell = tableView.dequeueReusableCell(withIdentifier: identifier, for: indexPath)
return castable(cell) { (c: PinkCell) in
c.fill(withModel: indexPath.row)
}
.match { (c: GrayCell) in
c.fill(withModel: "row = \(indexPath.row), column = \(indexPath.section)")
}
.extract()
}
要运行示例项目,首先克隆仓库,然后从Tests/iOS目录运行pod install
。
Swift 3.0
IDPCastable可通过CocoaPods获取。要安装它,只需将以下行添加到您的Podfile中
pod "IDPCastable"
Oleksa ‘trimm’ Korin,[email protected]
IDPCastable适用于新BSD许可证。有关更多信息,请参阅LICENSE文件。