In Swift, if a closure holds only a single statement, it automatically returns the value returned from that single statement.
This does not feel very natural in all cases. Let's look at an example:
func StringReturningFunc() -> String {
return "Test String"
}
// Error: Cannot convert the expressions type '() -> $T0' to type 'String'
let closure: () -> () = {
StringReturningFunc()
}
As you can see, even though the closure should only call a simple function, it tries to automatically return it's return value, which is of type String
, and does not match the return type void
.
I can prevent this by implementing the closures body like so:
let _ = StringReturningFunc()
Which feels incredibly odd.
Is there a better way to do this or is this just something I have to live with?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…