I would like to extend the Array class, but only for elements which conform to the SequenceType protocol.
The code I would like to write / the code I think would be sensible is:
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 create two versions of T. I assume one comes from the normal Array declaration, and the other from the attempted constraint on my method.
In particular, this means that line [1] gives the lovely error 'T' is not convertible to 'T'.
Similarly, the line at [2] fails, because in that context Swift does not recognise T as having a .Generator member (although the return type annotation in the declaration is valid).
I've tried a number of other formulations (including using, eg, T where T: SequenceType), but I can't seem to find a way to express this constraint.
Is this possible, or am I barking up the wrong tree?
func flatten<T: SequenceType>(array: [T]) -> [T.Generator.Element] {...