devxoul / Then

✨ Super sweet syntactic sugar for Swift initializers
MIT License
4.18k stars 290 forks source link

Add extension for AnyObject to get rid of 'return' statement. #21

Closed devxoul closed 8 years ago

devxoul commented 8 years ago

Problem

When using a closure with single line:

let user = User() {
    $0.name = "abc"
}

Then Swift compiler says:

error: cannot convert value of type '_ -> ()' to expected argument type 'inout User -> Void'

A possible workaround until now is adding a return statement.

let user = User() {
    $0.name = "abc"
    return
}

Solution

The cause of the error is: an inout parameter. It seemed like a Swift bug. In order to get rid of return statement, I've made a new extension on AnyObject that doesn't use inout parameter.

Limitation

This workaround is only available for reference types.