Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One-line closure without return type

Tags:

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?

like image 625
IluTov Avatar asked Jun 10 '14 20:06

IluTov


People also ask

How many types of closures are there in Swift?

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.

Why closures are reference types?

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.

What are type of closures?

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.

What is an escaping closure?

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.


1 Answers

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

like image 100
Joshua Weinberg Avatar answered Sep 29 '22 03:09

Joshua Weinberg