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.
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 🎉.
#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 }
🤓.
No comments yet. Share on Mastodon and see your comment or write a post on your blog if you support Webmentions
No reposts yet. Share on Mastodon and see your repost or write a post on your blog if you support Webmentions
No likes yet. Share on Mastodon and see your like or write a post on your blog if you support Webmentions
No bookmarks yet. Share on Mastodon and see your bookmark or write a post on your blog if you support Webmentions
Powered by Webmentions