Reputation: 27611
In learning Swift, I came across this code: -
enum ServerResponse {
case Result(String, String)
case Error(String)
}
for i in 1...10{
let mySuccess: ServerResponse = {
let zeroOrOne = rand() % 2
if zeroOrOne == 0 {
return ServerResponse.Result("7:00 am", "8.09 pm")
} else {
return ServerResponse.Error("Out of cheese.")
}
}()
var serverResponse: String
switch mySuccess {
case let .Result(sunrise, sunset):
serverResponse = "Sunrise is at \(sunrise) and sunset as \(sunset)"
case let .Error(error):
serverResponse = "Failure... \(error)"
}
println(serverResponse)
}
As can be seen here, there are parentheses () after the closing end brace of the declaration for:
let mySuccess: ServerResponse = {
...
}()
Without the parenthesis, playground produces the error:-
Function produces expected type 'ServerResponse'; did you mean to call it with ()?
Considering a function has the signature: -
func name(param) -> returnType
Can someone please explain why the parenthesis are required here? Is it a form of minimised closure, or something else?
Upvotes: 3
Views: 232
Reputation: 22487
Your ServerResponse
is not a function, it is an enum
, but without the parentheses the block you would be trying to assign to mySuccess
IS a function (that returns a ServerResponse
), and therefore cannot be assigned to a ServerResponse
. The result of calling the function (adding the parentheses) can be.
Upvotes: 2
Reputation: 59994
It's an anonymous function/lambda/closure (however you want to call it exactly), taking no argument, and whose return type is inferred by the compiler, which is then called immediately. It's similar to (function() {…})()
in JavaScript.
It has the big advantage of allowing you to define mySuccess
as a constant instead of a variable. Additionally, it creates a scope, such that intermediary variables (like zeroOrOne
) are not visible outside.
What I'm wondering is just why the author of this code didn't use the same style to define and assign serverResponse
…
Upvotes: 2