【发布时间】:2017-09-26 23:01:39
【问题描述】:
我已经阅读了 Apple 的 Swift iBook(类型转换和协议)的相关部分,但我似乎找到了一种方法来指定对象是符合特定协议的特定类的实例。
作为tableView(_: , cellForRowAt: ) 中的示例,我想将tableView.dequeueReusableCell(withIdentifier: reuseID, for: indexPath) 返回的单元格转换为符合RLMEntityCapableCell 协议的UITableViewCell 的子类(只需指定conformers 有一个名为item 的变量这是Object 或其子类之一的实例。
这条路线可行,但 双重转换 似乎过度:
protocol RLMEntityCapableCell: class {
var item: Object { get set }
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: reuseID, for: indexPath) as! RLMEntityCapableCell // Cast here so we can set item
cell.item = items[indexPath.row]
return cell as! UITableViewCell // Cast again so the return type is right…
}
另一种方法:
var cell = tableView.dequeueReusableCell(withIdentifier: reuseID, for: indexPath)
as! RLMEntityCapableCell, UITableViewCell
给出这个错误:
模式中缺少类型注释
显然也不是正确的做法。
我更愿意指定,为了符合协议,对象必须从UITableViewCell 或UICollectionViewCell 继承,但协议的基础只能限于类类型,不能进一步。
编辑:
这里的想法是为 Realm 对象提供一个通用数据源,该数据源利用泛型,就像 Array 和 Dictionary 所做的那样。每个表格视图中使用的单元格将特定于要显示的实体,但数据源只知道该单元格将是符合RLMEntityCapableCell 的UITableViewCell 的子类。所有数据源需要担心的是告诉单元格它需要显示什么实例(它始终是Object 的子类),单元格会从那里获取它并根据需要配置自己。
【问题讨论】:
标签: ios swift swift3 swift-protocols existential-type