FlatMap does not filter out zero when ElementOfResult is considered optional

Quick flatMap documentation:

Returns an array containing the non-nil results of the given transformation with each element of this sequence.

In the following examples, when the return type is ElementOfResultleft to the compiler for output flatMap, it works as documented, but on line 5, when specified ElementOfResult, thus outputting to the type Optional<String>seems to flatMapstop the filtering nil.

Why is he doing this?

~ 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"
}
+1
source share
1 answer

Here is the definition flatMap()

public func flatMap<ElementOfResult>(_ transform: (Element) throws -> ElementOfResult?) rethrows -> [ElementOfResult]

resultTypeSpecified [String?], , ElementOfResult - Optional<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 })
+2

All Articles