Bumble 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. 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

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.

The article includes code examples showing exactly how the String Collection conformance turned correct-looking code into a type nightmare.

About This Article

Problem

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.

Solution

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.

Impact

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.