2017-02-28 35 views
1

我想定義Array(或Sequence或Collector?)的擴展,以便我可以使用NSIndexPath查詢自定義對象列表的列表,並獲取基於indexPath的部分和行。對數組中的數組進行Swift通用擴展

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

回答

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

謝謝!正是我在找什麼! – Sunkas