swift - Get column from 2D array – how to restrict array type in extension? -


i'd extend array in swift return single element in each array, or column, 2d array. far have:

extension array // goes here?     func getcolumn( column: int ) -> [ int ] {         return self.map { $0[ column ] }     } } 

i believe need somehow specify 2d array after where, have been unable figure out correct way that.

what correct syntax specifying 2d array after where?

i'm curious if there documentation how specify available after where in extension lives. couldn't find @ apple's swift extension documentation

thanks in advance.

you need constrain element type of array. subscript method defined in collectiontype protocol:

public protocol collectiontype : indexable, sequencetype {     // ...     public subscript (position: self.index) -> self.generator.element { }     // ... } 

therefore can define extension method arrays elements collections:

extension array element : collectiontype {     func getcolumn(column : element.index) -> [ element.generator.element ] {         return self.map { $0[ column ] }     } } 

example:

let = [[1, 2, 3], [4, 5, 6]] let c = a.getcolumn(1)  print(c) // [2, 5] 

you define additional subscripting method:

extension array element : collectiontype {     subscript(column column : element.index) -> [ element.generator.element ] {         return map { $0[ column ] }     } }  let = [["a", "b", "c"], [ "d", "e", "f" ]] let c = a[column: 2] print(c) // ["c", "f"] 

update swift 3:

extension array element : collection {     subscript(column column : element.index) -> [ element.iterator.element ] {         return map { $0[ column ] }     } } 

Comments

Popular posts from this blog

routing - AngularJS State management ->load multiple states in one page -

python - GRASS parser() error -

Swift game error message -