map and CompactMap and flatMap

 let scores = ["1", "2", "three", "four", "5"]

let mapped: [Int?] = scores.map { str in Int(str) }
// [1, 2, nil, nil, 5] - Two nil values as "three" and "four" are strings.

let compactMapped: [Int] = scores.compactMap { str in Int(str) }
// [1, 2, 5] - The nil values for "three" and "four" are filtered out.

Comments

Popular posts from this blog

iOS Questions (Swift Programming Language)

Dispatch techniques: Dynamic dispatch and Static Dispatch

What’s the difference between var and let? Which one would you choose for properties in a struct and Class why?