You need to constrain the Element
type of the array. The subscript method is defined in the CollectionType
protocol:
public protocol CollectionType : Indexable, SequenceType {
// ...
public subscript (position: Self.Index) -> Self.Generator.Element { get }
// ...
}
Therefore you can define an extension method for arrays whose elements are collections:
extension Array where Element : CollectionType {
func getColumn(column : Element.Index) -> [ Element.Generator.Element ] {
return self.map { $0[ column ] }
}
}
Example:
let a = [[1, 2, 3], [4, 5, 6]]
let c = a.getColumn(1)
print(c) // [2, 5]
You could even define it as an additional subscripting method:
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"]
Update for Swift 3:
extension Array where Element : Collection {
func getColumn(column : Element.Index) -> [ Element.Iterator.Element ] {
return self.map { $0[ column ] }
}
}
or as subscript:
extension Array where Element : Collection {
subscript(column column : Element.Index) -> [ Element.Iterator.Element ] {
return map { $0[ column ] }
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…