数组中数组的Swift泛型扩展

时间:2017-02-28 12:48:48

标签: swift generics swift-extensions

我想定义Array(或Sequence或Collector?)的扩展名,以便我可以使用NSIndexPath查询自定义对象的列表列表,并根据indexPath的section和row获取对象。 / p>

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]
    }
}

1 个答案:

答案 0 :(得分:3)

  • 无法通过下标对Sequence编制索引,因此您需要一个 Collection
  • 集合元素也必须是集合。
  • 由于.row.sectionInt,因此收集 并且其嵌套集合必须由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]
    }
}
相关问题