I\'m trying to write an extension to Array which will allow an array of optional T\'s to be transformed into an array of non-optional T\'s.
e.g. this could be writte
Since Swift 2.0 it is possible to add a method that works for a subset of types by using where
clauses. As discussed in this Apple Forum Thread this can be used to filter out nil
values of an array. Credits go to @nnnnnnnn and @SteveMcQwark.
As where
clauses do not yet support generics (like Optional
), a workaround is necessary via a Protocol.
protocol OptionalType {
typealias T
func intoOptional() -> T?
}
extension Optional : OptionalType {
func intoOptional() -> T? {
return self.flatMap {$0}
}
}
extension SequenceType where Generator.Element: OptionalType {
func flatten() -> [Generator.Element.T] {
return self.map { $0.intoOptional() }
.filter { $0 != nil }
.map { $0! }
}
}
let mixed: [AnyObject?] = [1, "", nil, 3, nil, 4]
let nonnils = mixed.flatten() // 1, "", 3, 4