The flatMap() method transforms optionals and arrays
About 2 min
The flatMap() method transforms optionals and arrays 관련
HACKING WITH SWIFT
What's new in Swift?
The flatMap() method transforms optionals and arrays | Changes in Swift 1.2
The flatMap() method transforms optionals and arrays
Available from Swift 1.2
The flatMap()
method is designed to allow you to transform optionals and elements inside a collection while also decreasing the amount of containment that happens. For example, if you transform an optional in a way that will also return an optional, using map()
would give you an optional optional (a double optional), whereas flatMap()
is able to combine those two optionals into a single optional.
let lengthOfFirst = names.first.flatMap { count($0) }
Decreasing the amount of containment also makes flatMap()
a simple way of converting multi-dimensional arrays into single-dimensional arrays:
[[1, 2], [3, 4], [5, 6]].flatMap { $0 }
There is no "map" operation there, so we're just left with the flattening behavior – that will result in a single array containing the value [1, 2, 3, 4, 5, 6]
.
Other changes in Swift 1.2…
The zip() function joins two sequences | Changes in Swift 1.2
The zip() function joins two sequences
Closures can now be marked @noescape | Changes in Swift 1.2
Closures can now be marked @noescape
Classes can now have static methods and properties | Changes in Swift 1.2
Classes can now have static methods and properties
Constants no longer require immediate initialization | Changes in Swift 1.2
Constants no longer require immediate initialization
A new Set data structure | Changes in Swift 1.2
A new Set data structure
Implicit bridging has been reduced | Changes in Swift 1.2
Implicit bridging has been reduced
Multiple if let bindings | Changes in Swift 1.2
Multiple if let bindings
Typecasting now includes as! | Changes in Swift 1.2
Typecasting now includes as!