Badoo Muhammad Shuaib Khan

Badoo's Swift 4.1 Introduction of CompactMap

Original post 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.

Continue reading

What This Article Covers

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.

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.

This page summarizes “Swift 4.1 Introduction of CompactMap” by Badoo, published Apr 16, 2018. All credit for the original work goes to the authors.

Read the original on badootech.badoo.com (opens in new tab)

AI tools for iOS

Browse all AI tools →