假设我有一个具有相同属性的 UICollectionViewCell 和 UITableViewCell。与其使用两个函数来填充这些单元格,不如使用一个泛型来获取某些东西,确定那是什么,然后将其转换为正确的东西,以便在返回之前对其执行操作?
我的想法是:
func setUpCell<T>(event: Event, cell:T) -> T {
// figure out what T is and cast it
cell.event.bar = event.bar
return cell
}
这是避免大量代码重复的好方法吗?
最佳答案
给定你的模型类型
struct Event {
let title: String
let desc: String
}
定义这个协议(protocol)
protocol EventCell: class {
var id: String? { get set }
var desc: String? { get set }
}
现在让你的 UITabelViewCell
和 UICollectionViewCell
符合它
class TableCell: UITableViewController, EventCell {
var id: String?
var desc: String?
}
class CollectionCell: UICollectionViewCell, EventCell {
var id: String?
var desc: String?
}
最后定义这个扩展
extension EventCell {
func populate(event:Event) {
self.id = event.id
self.desc = event.desc
}
}
就是这样。现在你的两个单元格(UITabelViewCell
和 UICollectionViewCell
)都有 populate
方法!
关于swift - 在通用的 swift 函数中进行类型转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36113489/