NOTE: This question was asked while Swift 2.1 was the latest.
Given:
class IntWrapper {
var i: Int = 1
}
func add(inout m: Int, i: Int) {
m += i
}
And a higher order function
func apply() -> (inout i: Int) -> () -> () {
return { (inout i: Int) -> () -> () in
return {
add(&i, i: 1)
}
}
}
Application as so results in the member variable value never changing:
var intW = IntWrapper()
print(intW.i) // Prints '1'
apply()(i: &intW.i)()
print(intW.i) // Prints '1'
However, when changing the function to curried form
func apply()(inout i: Int)() -> () {
add(&i, i: 1)
}
Application results in the member variable value changing:
var intW = IntWrapper()
print(intW.i) // Prints '1'
apply()(i: &intW.i)()
print(intW.i) // Prints '2'
I'm curious to why this is. I always thought that curried syntax was sugar for the higher ordered form of the function, but apparently there are semantic differences.
Additionally this accepted proposal to remove curried syntax from swift seems to state this is merely sugar, and I'm concerned we're losing more than syntax by removing this from the language. Is there a way to get the same functionality from a higher order function?


来源:https://stackoverflow.com/questions/35423428/swift-subtle-difference-between-curried-and-higher-order-function