flatmap的swift文档如下:
返回一个数组,该数组包含调用给定
与此序列的每个元素的转换。
在下面的示例中,当编译器保留ElementOfResult的返回类型以推断flatMap的工作方式时,如文档所述,但是在第5行指定了ElementOfResult时,因此推断为Optional<String>类型时,flatMap似乎停止筛选出nil
为什么要这么做?

~ swift
Welcome to Apple Swift version 3.0.2 (swiftlang-800.0.63 clang-800.0.42.1). Type :help for assistance.
  1> let words = ["1989", nil, "Fearless", nil, "Red"]
words: [String?] = 5 values {
  [0] = "1989"
  [1] = nil
  [2] = "Fearless"
  [3] = nil
  [4] = "Red"
}
  2> words.flatMap { $0 }
$R0: [String] = 3 values {
  [0] = "1989"
  [1] = "Fearless"
  [2] = "Red"
}
  3> let resultTypeInferred = words.flatMap { $0 }
resultTypeInferred: [String] = 3 values {
  [0] = "1989"
  [1] = "Fearless"
  [2] = "Red"
}
  4> let resultTypeSpecified: [String?] = words.flatMap { $0 }
resultTypeSpecified: [String?] = 5 values {
  [0] = "1989"
  [1] = nil
  [2] = "Fearless"
  [3] = nil
  [4] = "Red"
}

最佳答案

以下是flatMap()的定义
public func flatMap<ElementOfResult>(_ transform: (Element) throws -> ElementOfResult?) rethrows -> [ElementOfResult]
当您将resultTypeSpecified的类型设置为[String?]时,您将告诉编译器ElementOfResultOptional<String>
转换闭包的类型为(String?) -> Optional<Optional<String>>
flatMap将去掉1“层”的选项,而不是2层。
希望这个例子能让事情更清楚:

let input: [String??] = [
    Optional.some(Optional.some("1989")),
    Optional.some(Optional.none),
    Optional.some(Optional.some("Fearless")),
    Optional.some(Optional.none),
    Optional.some(Optional.some("Red"))
]

let output = input.flatMap({ $0 })

09-27 10:03