Swift 4.1 Introduction of CompactMap
Article Summary
Muhammad Shuaib Khan from Bumble Tech explains why Swift 4.1 killed off a popular method that was secretly breaking code. The culprit? A function that worked too well in the wrong places.
Swift's flatMap had three overloaded versions, but one was causing silent bugs when developers used it incorrectly. When String became a Collection in Swift 4.0, innocent-looking code started returning completely wrong types without any compiler errors. Apple's solution was radical: deprecate the problematic overload entirely.
Key Takeaways
- flatMap had three overloads, but one matched both optional unwrapping and sequence flattening
- String conforming to Collection broke existing flatMap code silently after Swift 4.0
- compactMap now handles nil filtering, preventing misuse that returned Array<Character> instead of Array<String>
- The change enforces functional programming definitions: map transforms 1:1, flatMap flattens sequences
Swift 4.1 introduced compactMap to replace flatMap's nil-filtering behavior, preventing a common misuse pattern that caused type mismatches without compiler warnings.
About This Article
Swift's flatMap method had three competing overloads that made it hard for the compiler to figure out what developers wanted. One handled sequences returning sequences, another worked with optionals, and a third dealt with sequences where the closure returned optionals. This overlap meant the compiler couldn't always tell which version you meant to use.
Apple removed the problematic third overload in Swift 4.1. Muhammad Shuaib Khan's Bumble Tech team documented this change. In its place came compactMap, a new method built specifically to filter out nil values without the confusion of multiple overload options.
With compactMap in place, Swift 4.1 fixed a real problem where flatMap on String arrays would silently return Array<Character> instead of Array<String>. The compiler no longer let these type mismatches slip through unnoticed.