IluTov
IluTov

Reputation: 6862

One-line closure without return type

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?

Upvotes: 25

Views: 7390

Answers (2)

Ondrej Rafaj
Ondrej Rafaj

Reputation: 4417

What about this ... ;)

@discardableResult func StringReturningFunc() -> String {
    return "Test String"
}

// Error: Cannot convert the expressions type '() -> $T0' to type 'String'
let closure: () -> () = {
    StringReturningFunc()
}

Upvotes: 0

Joshua Weinberg
Joshua Weinberg

Reputation: 28688

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

Upvotes: 26

Related Questions