Syntax of the type of closure return

advertisements

I have the following closure within a struct thats causing some confusion.

var response: (result: Result<UserInfo>) -> Void

struct RegisterRequest: Requestable
{
    let userInfo : [String:AnyObject]
    var response: (result: Result<UserInfo>) -> Void
}

Now when I try to implement it, I have the following:

let register = RegisterRequest(userInfo: userInfo, response: { (result) in
})

If closure syntax is

{ (params) -> returnType in
   statements
}

Why is swift auto correcting my implementation to (result) in instead of (Void) in


The block variable response is expected to take a single parameter whose type is Result, not Void or (). Thus, Xcode automatically fills in with an argument named result representing a Result object. Since return type is Void, anything after -> can simply be omitted.

More explicitly, it would be written as:

..., response: { (result: Result<UserInfo>) -> Void in
})

For the sake of simplicity, it is converted to:

..., response: { (result) in
})

Parenthesis around arguments can also be omitted:

..., response: { result in
})

If you don't want the block taking any parameter, you can define type of that as one of the below:

var response: (Void) -> Void
var response: () -> Void