hello,
when using defer
statement it is very tempting to have an ability to grab the function return value without introducing a special variable and tracking it manually. consider this example:
func foo1(param1: Int, param2: Int?, param3: UnsafePointer<Float>?) -> Int {
defer { trace($functionReturnValue) }
guard param1 > 0 else {
return -1
}
guard let param2 = param2 else {
return -2
}
guard let param3 = param3 else {
return -3
}
return some(param1: param1, param2: param2, param3: param3)
}
in order to write this today you have to introduce a variable, and always remember to assign it before returning:
func foo2(param1: Int, param2: Int?, param3: UnsafePointer<Float>?) -> Int {
var result = 0
defer { trace(result) }
guard param1 > 0 else {
result = -1
return result
}
guard let param2 = param2 else {
result = -2
return result
}
guard let param3 = param3 else {
result = -3
return result
}
result = some(param1: param1, param2: param2, param3: param3)
return result
}
the obvious problem here is that it is very easy to forget to assign the variable:
return -3
or mistakenly use a different variable:
let result = -3
return result
to be less verbose you can introduce a helper function:
func setResult<T>(_ v: inout T, _ val: T) -> T {
v = val
return val
}
and use it like so:
func foo3(param1: Int, param2: Int?, param3: UnsafePointer<Float>?) -> Int {
var result = 0
defer { trace(result) }
...
guard let param3 = param3 else {
return setResult(&result, -3)
}
return setResult(&result, some(param1: param1, param2: param2, param3: param3))
}
this is shorter but at the same time more awkward looking and is still easy to forget to do.
was ability to get the function return value discussed? how do you feel about adding this new feature to swift? this is a pure additive feature, hopefully not too hard to implement.