我想定义 Array(或 Sequence 或 Collector?)的扩展,以便我可以使用 NSIndexPath 查询自定义对象列表的列表,并根据 indexPath 的部分和行获取对象。
public var tableViewData = [[MyCellData]]() // Populated elsewhere
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var tableViewCellData = tableViewData.data(from: indexPath)
// use tableViewCellData
}
// This does not compile as I want the return type to be that of which is the type "in the list in the list" (i.e. MyCellData)
extension Sequence<T> where Iterator.Element:Sequence, Iterator.Element.Element:T {
func object(from indexPath: NSIndexPath) -> T {
return self[indexPath.section][indexPath.row]
}
}
最佳答案
- A
Sequence
不能通过下标索引,所以你需要一个Collection
. - 集合元素也必须是集合。
- 自
.row
,.section
是Int
, 集合 其嵌套集合必须由Int
索引. (许多集合都是这种情况,例如数组或数组切片。String.CharacterView
是一个不是的集合的例子 由Int
索引.) - 您不需要任何通用占位符(和
extension Sequence<T>
不是有效的 Swift 3 语法)。只需将返回类型指定为 嵌套集合的元素类型。
综合起来:
extension Collection where Index == Int, Iterator.Element: Collection, Iterator.Element.Index == Int {
func object(from indexPath: IndexPath) -> Iterator.Element.Iterator.Element {
return self[indexPath.section][indexPath.row]
}
}
关于数组中数组的 Swift 通用扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42509193/