您需要约束
Element
数组的类型。下标方法在
CollectionType
协议:
public protocol CollectionType : Indexable, SequenceType {
// ...
public subscript (position: Self.Index) -> Self.Generator.Element { get }
// ...
}
因此,您可以为元素为集合的数组定义扩展方法:
extension Array where Element : CollectionType {
func getColumn(column : Element.Index) -> [ Element.Generator.Element ] {
return self.map { $0[ column ] }
}
}
let a = [[1, 2, 3], [4, 5, 6]]
let c = a.getColumn(1)
print(c) // [2, 5]
extension Array where Element : CollectionType {
subscript(column column : Element.Index) -> [ Element.Generator.Element ] {
return map { $0[ column ] }
}
}
let a = [["a", "b", "c"], [ "d", "e", "f" ]]
let c = a[column: 2]
print(c) // ["c", "f"]
更新
Swift 3:
extension Array where Element : Collection {
func getColumn(column : Element.Index) -> [ Element.Iterator.Element ] {
return self.map { $0[ column ] }
}
}
或作为下标:
extension Array where Element : Collection {
subscript(column column : Element.Index) -> [ Element.Iterator.Element ] {
return map { $0[ column ] }
}
}