Supporting compactMap in Swift 4
Swift 4.1 is shipping soon with many wonderful things! One of the changes that may affect you is usage of flatMap
to remove nil
from your Sequence.
1
2
let names = ["Maria", nil, "Daniel"]
names.flatMap { $0 } //=> ["Maria", "Daniel"]
Backwards Compatibility
I wanted to ensure I avoided dealing with migration errors/assistant as much as possible. Lucky for us, Swift is a powerful language.
We can define an extension Sequence.compactMap
for any version below 4.1 🎉.
1
2
3
4
5
6
7
8
9
#if swift(>=4.1)
// This will be provided by the stdlib
#else
extension Sequence {
func compactMap<T>(_ transform: (Self.Element) throws -> T?) rethrows -> [T] {
return try flatMap(transform)
}
}
#endif
With the extension in place, we can change our usage of .flatMap { $0 }
to .compactMap { $0 }
🤓.