数组中数组的 Swift 通用扩展

标签 swift generics swift-extensions

我想定义 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 , .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]
    }
}

关于数组中数组的 Swift 通用扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42509193/

相关文章:

ios - SKCloudServiceController().requestUserToken 在 iOS 14.2 上卡住

swift - 带有计时器类的 UIView 可以防止 deinit

swift - 将 CloudKit RecordID 保存到 CoreData

java - 使用 mockito 模拟使用通配符返回泛型的方法

arrays - 将 TArray 分配给 T 数组

oop - 如何向必须实现所需初始值设定项的子类添加所需属性?

objective-c - 如何制作枚举案例的开关案例(快速)

c# - 如何将泛型类型列表作为参数传递给 xamarin-C#-ios 中 TableSource 的构造函数?

swift - 在 Swift 中,你能写一个扩展,它返回扩展所在类的类型化实例吗?

swift - 通过扩展实现协议(protocol)