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
Swift 4.1 introduced compactMap to replace flatMap's nil-filtering behavior, eliminating a confusing overload that caused type mismatches and silent logic bugs.
About This Article
Swift's flatMap method had three overloaded variants that did different things. This created confusion because developers could call the wrong version without the compiler catching it.
Swift 4.1 removed the overload that filtered out nil values and added compactMap instead. Muhammad Shuaib Khan and the Bumble Tech team documented this change. compactMap is clearer about what it does when working with optional values in sequences.
This fixed a bug where flatMap on String collections would return Array<Character> instead of Array<String>. These mistakes happened silently and could cause logic errors in production. The code would still compile, so developers wouldn't notice the problem.