Badoo Muhammad Shuaib Khan Apr 16, 2018

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

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.

The article reveals the exact code pattern that looked correct but silently broke after Swift 4.0, and why even experienced developers fell into this trap.

About This Article

Problem

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.

Solution

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.

Impact

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.