Skip to content

Instantly share code, notes, and snippets.

@natecook1000
Forked from chriseidhof/Main.swift
Last active August 29, 2015 14:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save natecook1000/4d790d4556f9919aacb6 to your computer and use it in GitHub Desktop.
Save natecook1000/4d790d4556f9919aacb6 to your computer and use it in GitHub Desktop.
protocol OptionalType {
typealias T
func flatMap<U>(@noescape f: (T) -> U?) -> U?
}
extension Optional : OptionalType { }
extension SequenceType where Generator.Element: OptionalType {
func flatten() -> [Generator.Element.T] {
return self.map { $0.flatMap { $0 } }
.filter { $0 != nil }
.map { $0! }
}
}
let z: [Int?] = [1, 2, nil, 3]
let flatz = z.flatten() // 1, 2, 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment