func oneStepForward(_ input: Int) -> Int {
return input + 1
}
func oneStepBackward(_ input: Int) -> Int {
return input - 1
}
func chooseStepFunction(backward: Bool) -> (Int) -> Int {
return backward ? oneStepBackward : oneStepForward
//Error. type of expression is ambiguous without a type annotation
}
Why am I getting this error ?
If I change this function to the following it works and will compile.
func chooseStepFunction(backward: Bool) -> (Int) -> Int {
if backward {
return oneStepBackward
} else {
return oneStepForward
}
}
// Why am I getting the error in the previous version while it works in the second version ?
Thx in advance.
Yeah, this is definitely bugworthy. Dinisan, I’d appreciate you filing a bug about this, and then posting the bug number here, just for the record.
Given these:
func stepForward(_ input: Int) -> Int {
input + 1
}
func stepBackward(_ input: Int) -> Int {
input - 1
}
then these two fail:
func chooseStepFunctionNG1(backward: Bool) -> (Int) -> Int {
backward ? stepBackward : stepForward
}
func chooseStepFunctionNG2(backward: Bool) -> (Int) -> Int {
backward ? stepBackward(_:) : stepForward(_:)
}
but these three succeed:
func chooseStepFunctionOK1(backward: Bool) -> (Int) -> Int {
if backward {
stepBackward
} else {
stepForward
}
}
func chooseStepFunctionOK2(backward: Bool) -> (Int) -> Int {
backward ? (stepBackward as (Int) -> Int) : (stepForward as (Int) -> Int)
}
func chooseStepFunctionOK3(backward: Bool) -> (Int) -> Int {
let result = backward ? stepBackward : stepForward
return result
}
The gating factor seems to be type resolution with function types between the function result and the ?:
operator. Fun times.
It works in iOS playground, but not in macOS playground
FWIW, I’m seeing it in both playground types, and also in a macOS > Command Line Tool target, which is by far the best way to test weird stuff like this (Playgrounds have all sorts of sharp edges). And yeah, in both Xcode 16.4 and Xcode 26.0b6.
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"