Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
622 views
in Technique[技术] by (71.8m points)

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

I'd like to extend Array in Swift to return a single element in each array, or column, for a 2D array. So far I have:

extension Array where // what goes here?
    func getColumn( column: Int ) -> [ Int ] {
        return self.map { $0[ column ] }
    }
}

I believe that I need to somehow specify a 2D array after where, but I have been unable to figure out the correct way to do that.

What is the correct syntax for specifying a 2D array after the where?

I'm also curious if there is a good documentation for how to specify what is available for after where in an extension lives. I couldn't find that at Apple's Swift extension documentation

Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...