Function types as return types

Greetings, func stepForward(_ input: Int) -> Int { return input + 1 } func stepBackward(_ input: Int) -> Int { return input - 1 } func chooseStepFunction(backward: Bool) -> (Int) -> Int { return backward ? stepBackward : stepForward /* Error type of expression is ambiguous without a type annotation */ } Why am I getting this error. If I change the function to func chooseStepFunction(backward: Bool) -> (Int) -> Int { if backward { return stepBackward else { return stepForward } } Why is the previous chooseStepFunction giving me an error ? Thx in advance

Answered by DTS Engineer in 855056022

Let’s focus this discussion on your other thread.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

I am sorry about this post . I made a mistake with the formatting. I have posted an improved version

If you make a mistake in your post you have a one-hour window in which you can edit it. If you're outside of that one hour, just reply to your original post. There's no need to create a duplicate thread for the same issue just because you didn't format something properly; that just clutters the forums.

Anyway, correctly formatted:

func stepForward(_ input: Int) -> Int {
	input + 1
}

func stepBackward(_ input: Int) -> Int {
	input - 1
}

func chooseStepFunction(backward: Bool) -> (Int) -> Int {
	backward ? stepBackward : stepForward
}

// Second version
func chooseStepFunction(backward: Bool) -> (Int) -> Int {
	if backward {
		stepBackward

	} else {
		stepForward
	}
}

I don't get any errors, so this can't be the code that's causing it. The first version with the ternary operator works fine.

As an aside, in Swift, if your function only does one thing then you don't need the return keyword.

Let’s focus this discussion on your other thread.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

Function types as return types
 
 
Q