Mobile Development Swift Subjective
Oct 04, 2025

What is the difference between map, flatMap, and compactMap?

Detailed Explanation
These are higher-order functions for transforming collections with different behaviors.\n\n• **map:**\n• Transforms each element using a closure\n• Returns array of same size\n• One-to-one transformation\n\n\nlet numbers = [1, 2, 3, 4]\nlet doubled = numbers.map { $0 * 2 }\n// Result: [2, 4, 6, 8]\n\n\n• **compactMap:**\n• Transforms and removes nil values\n• Returns array with non-nil results\n• Filters out optionals\n\n\nlet strings = ["1", "2", "abc", "4"]\nlet numbers = strings.compactMap { Int($0) }\n// Result: [1, 2, 4]\n\n\n• **flatMap:**\n• Transforms and flattens nested collections\n• Removes one level of nesting\n• Useful for nested arrays\n\n\nlet nestedArrays = [[1, 2], [3, 4], [5, 6]]\nlet flattened = nestedArrays.flatMap { $0 }\n// Result: [1, 2, 3, 4, 5, 6]\n\n// With transformation\nlet words = ["hello", "world"]\nlet characters = words.flatMap { $0 }\n// Result: ["h", "e", "l", "l", "o", "w", "o", "r", "l", "d"]\n\n\n• **Key Differences:**\n• map: 1:1 transformation\n• compactMap: 1:0 or 1:1 (removes nils)\n• flatMap: 1:many (flattens collections)
Discussion (0)

No comments yet. Be the first to share your thoughts!

Share Your Thoughts
Feedback