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
Critical Insight
Swift 4.1 introduced compactMap to replace flatMap's nil-filtering behavior, preventing a common misuse pattern that caused type mismatches without compiler warnings.