Swift 4.1: Introduction of CompactMap
Article Summary
Muhammad Shuaib Khan from Bumble Tech explains why Swift 4.1 killed off a popular method. The culprit? A naming confusion that was breaking code in subtle, dangerous ways.
Swift's flatMap had three different overloads doing very different things, and one was causing silent bugs when developers thought they were using map. When String became a Collection in Swift 4.0, innocent-looking code started returning completely wrong types without any compiler errors.
Key Takeaways
- flatMap had 3 overloads: one flattened sequences, one handled optionals, one removed nils
- The nil-removal version didn't actually flatten, making it closer to map than flatMap
- String conforming to Collection broke existing flatMap code silently (Array<String> became Array<Character>)
- compactMap now handles the nil-removal case with a clearer, dedicated method
- The change prevents misuse where flatMap worked but map was the right choice
Critical Insight
Swift 4.1 introduced compactMap to replace flatMap's nil-filtering behavior, eliminating a confusing overload that caused type mismatches and silent logic bugs.