It seems Optional.map()
when the transform
closure returns nil
, then result is Optional(nil)
, which is same as Optional.some(nil)
? Still a nil
but is wrap up an optional? But Optional.flatMap()
when the transform
closure returns nil, the result is just nil
, which is simpler. Why not just always use flatMap
, I want to ask?
There must be reason we have both Optional.map()
and Optional.flatMap()
? Any good explanation?
let anOptional: Int? = 123
let aNilValue: Int? = nil
// Trailing closure in this context is confusable with the body of the statement; pass as a parenthesized argument to silence this warning
let g = anOptional.map {_ in aNilValue }
print("optional.map returns: \(g)")
//prints: optional.map returns: Optional(nil)
let h = anOptional.flatMap {_ in aNilValue }
print("optional.flatMap returns: \(h)")
//prints: optional.flatMap returns: nil