Last active
February 1, 2019 16:54
-
-
Save RoyalIcing/b89800081ce28db4be04 to your computer and use it in GitHub Desktop.
Swift compact() for SequenceType
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//: Playground - noun: a place where people can play | |
import Foundation | |
protocol OptionalParasite { | |
typealias WrappedParasite | |
func toArray() -> [WrappedParasite] | |
} | |
extension Optional: OptionalParasite { | |
typealias WrappedParasite = Wrapped | |
func toArray() -> [WrappedParasite] { | |
return flatMap { [$0] } ?? [] | |
} | |
} | |
extension ImplicitlyUnwrappedOptional: OptionalParasite { | |
typealias WrappedParasite = Wrapped | |
func toArray() -> [WrappedParasite] { | |
return flatMap { [$0] } ?? [] | |
} | |
} | |
extension SequenceType where Generator.Element: OptionalParasite { | |
func compact() -> [Generator.Element.WrappedParasite] { | |
return flatMap { element in | |
return element.toArray() | |
} | |
} | |
} | |
let abc: [Int?] = [ | |
54, | |
46, | |
nil, | |
22, | |
1, | |
nil | |
] | |
abc.compact() | |
// [54, 46, 22, 1] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here is a version that works with swift 4.2: