For instance, we have the following code

func testFunc<T>(_ value: T) {
    // do something
}

// This overloaded function is provided on a newer version of SDK, we need to check the SDK version.
func testFunc<T>(_ value: T?) {
    // do something if we have an optional value
}

If I have an optional value, how can I specify that I want to call the first function instead of the second function? The rationale behind this is that the second function may only be available on a newer SDK, so I need to have fallback.

2 Answers

0
Joey On

Swift tries to pick the most specific function possible. So to call testFunc<T>(_ value: T) you have to pass there a non-optional T. If you pass there an optional or force-unwrapped T second function testFunc<T>(_ value: T?) will be called.
You can not explicitly tell compiler which overloaded function to use, you can only modify parameters so they exactly match overloaded function you want to call.

This snippet guarantees, that testFunc<T>(_ value: T) will be called

let optional: Int? = 5
if let optional = optional {
   testFunc(optional)
}
-1
iDevid On
if let value = value {
    testFunc(value)
}