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?
As shown in the above table, there are three types of closures in Swift, namely global functions, nested functions, and closure expressions. They differ in several aspects, including their use scopes, their names, and whether they capture values, which will be discussed more in a later section.
Closures Are Reference TypesWhenever you assign a function or a closure to a constant or a variable, you are actually setting that constant or variable to be a reference to the function or closure.
There are many different types of closures that perform a variety of functions. Some common types of closures include continuous thread closures (CT), disc top caps, child resistant (CRC) closures, pumps, and sprayers. A CT cap is your basic closure that can be easily sealed and resealed.
An escaping closure is a closure that's called after the function it was passed to returns. In other words, it outlives the function it was passed to. A non-escaping closure is a closure that's called within the function it was passed into, i.e. before it returns.
The reason this happens is the shorthand for single line expression closures. There is an implicit 'return' in your closure as it is written.
let closure: () -> () = { StringReturningFunc() return }
Writing it like that should work
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With