let possibleNumbers = ["1", "2", "three", "///4///", "5"]
let mapped: [Int?] = possibleNumbers.map { str inInt(str) }
[1, 2, nil, nil, 5]
//////////////////////////////////////////////
let compactMapped: [Int] = possibleNumbers.compactMap { str in Int(str) }
[1, 2, 5]
flatMap
相比较map和compactMap,flatMap具有一定的迷惑性。
作为去nil功能时,它过期了
比如你这么写函数,会得到一个告警:
看源代码,上面也说得非常的清晰,过期了:
@available(swift, deprecated: 4.1, renamed: "compactMap(_:)", message: "Please use compactMap(_:) for the case where closure returns an optional value")
publicfuncflatMap<ElementOfResult>(_transform: (Element) throws -> ElementOfResult?) rethrows -> [ElementOfResult]
extensionCollection {
@inlinablepublicfuncmap<T>(
_transform: (Element) throws -> T
) rethrows -> [T] {
// TODO: swift-3-indexing-model - review the followinglet n =self.count
if n ==0 {
return []
var result =ContiguousArray<T>()
result.reserveCapacity(n)
var i =self.startIndex
for_in0..<n {
result.append(try transform(self[i]))
formIndex(after: &i)
_expectEnd(of: self, is: i)
returnArray(result)