Search code examples
swiftvariable-declaration

What does the parentheses mean in this var declaration?


I'm new to Swift and I just saw this declaration:

var completionHandlers = [(String) -> Void]()

As far as I know, this line is declaring an array of closures of type (String) -> Void, but I'm not sure of what the parentheses mean there.


Solution

  • The parenthesis is a way of calling the initialiser.

    This is equivalent to:

    var completionHandlers: [(String) -> Void] = []
    

    Another way you will see it is:

    var completionHandlers: [(String) -> Void] = .init()
    

    You see it when initialising empty collections because if, for example you had:

    var someVariable = ["hello", "world"]
    

    The compiler would be able to infer the type of someVariable to be [String] because it knows the type of the contents. but You can't initialise an empty array like this because there is no information about the type. so [(String) -> Void]() is a way of providing the type to the empty initialiser.

    The general recommendation in Swift is to use Type Inference where the type of the variable is inferred from it's initial value:

    let intVariable = 3
    let stringVariable = "Hello"
    //etc
    

    The style of code in your question follows this.

    But in some cases with more complex types this can slow down the compiler, so many people are more explicit with their variable declarations.

    let intVariable: Int = 3
    let stringVariable: String = "Hello"
    

    It's a matter of taste (and argument).