Can you extend a general class (e.g. an array) with specific restrictions?

I would like to extend the class Array, but only for elements that conform to the protocol SequenceType.

The code I would like to write / code that I think would be reasonable:

extension Array {
    func flatten<T: SequenceType>() -> [T.Generator.Element] {
        var result = [T.Generator.Element]() // *** [2]

        for seq: T in self { // *** [1]
            for elem in seq {
                result += [elem]
            }
        }

        return result
    }
}

However, Swift seems to be creating two versions T. I assume this comes from a regular declaration Array, and the other from an attempt to limit my method.

In particular, this means that line [1] gives an excellent error 'T' is not convertible to 'T'.

Similarly, the line in [2] fails because in this context Swift does not recognize it Tas having a member .Generator(although the annotation in the type of the returned declaration in the declaration is valid).

( , , T where T: SequenceType), . , ?

+4
2

, , - . Swift , . ( , Swift.) , , contains Swift. , - , Equatable. , . , . (, , .)

, Swift , "" flatten, join, , join([], arrayOfArrays).

+2

Swift 2 :

extension SequenceType where Generator.Element : SequenceType {
    func flatten() -> [Generator.Element.Generator.Element] {
        var result: [Generator.Element.Generator.Element] = []
        for seq in self {
            result += seq
        }
        return result
    }
}

[[1,2,3],[],[2,4,5]].flatten() // [1, 2, 3, 2, 4, 5]

, , flatMap .

+2

All Articles