Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weird behavior using the Swift Optional type

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? :)

like image 764
Bohdan Savych Avatar asked May 18 '26 15:05

Bohdan Savych


1 Answers

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)
like image 69
Martin R Avatar answered May 21 '26 04:05

Martin R



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!