Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding enum and function signature

Tags:

macos

swift

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?

like image 920
TheDarkKnight Avatar asked Apr 11 '26 15:04

TheDarkKnight


2 Answers

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

like image 73
Jean-Philippe Pellet Avatar answered Apr 13 '26 05:04

Jean-Philippe Pellet


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.

like image 23
Grimxn Avatar answered Apr 13 '26 07:04

Grimxn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!