I was practicing with Swift Optional type a little bit, and noticed weird(for me) behavior. Code:
func returnOptionalIntFromString(_ val: String) -> Int? {
return Int(val)
}
func returnIntFromString(_ val: String) -> Int {
return Int(val) ?? 0
}
let optionalStr: String? = "10"
let mappedC1 = optionalStr.map(returnIntFromString)
let mappedC2 = optionalStr.map(returnOptionalIntFromString)
let flatMappedC1 = optionalStr.flatMap(returnIntFromString)
let flatMappedC2 = optionalStr.flatMap(returnOptionalIntFromString)
Why this line let flatMappedC1 = optionalStr.flatMap(returnIntFromString) compiling? I'm passing (String) -> Int to the function which accept (String) -> Optional<Int>, so it must be compile-time error? Or no? :)
Optionals are treated specially by the compiler. In particular, a value
of type T is automatically wrapped into an Optional<T> if necessary:
let a = 5
let b: Int? = a
That works also with non-optional vs optional return types of a closure:
let cla: () -> Int = { return 13 }
let clb: () -> Int? = cla
and that is what happens in
let flatMappedC1 = optionalStr.flatMap(returnIntFromString)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With