Boring guide to Closures in Swift - Closure Expression Syntax

Jul 30, 20

In the first part we learnt about passing functions as parameters to other functions. But to just pass a function we need to write a lot code of creating another function. It can get tedious sometimes if the passed function does a simple job. So Swift provides several ways to directly write a code using a variety of syntaxes from somewhat verbose to very concise ways which are commonly known as Closure Expression Syntax

{ (parameters) -> return type in
    statements
}

So continuing from the previous example, if we try to call processString function our autocomplete in XCode will look something like this:

So if we compare the above image to the Closure Expression Syntax example:

  • String is the parameters
  • Void is the return type

So we can write process10Times method Closure Expression syntax as:

processString(stringValue: "String To Processed", process: { (string: String) in
    for _ in 0..<10 {
        print("Fast Processing \(string) more times...")
        sleep(1)
    }
})

and it will function the same way as:

processString(stringValue: "This is large string to process", process: process10Times)

Type infering in Closure Expression syntax

We can skip mentioning the data type of the parameter and our closure will infer it from the closure definition.

processString(stringValue: "String To Processed", process: { (string) in
    for _ in 0..<10 {
        print("Fast Processing \(string) more times...")
        sleep(1)
    }
})

Shorthand arguments

One of the shortest and most confusing way is using shorthand arguments.

processString(stringValue: "String To Processed", process: {
    for _ in 0..<10 {
        print("Fast Processing \($0) more times...")
        sleep(1)
    }
})

Here $0 represent the first parameter. In our closure we had only one parameter so we can only use $0. But if some closure has multiple parameters, they can be used as $0, $1, $2. It is better we use this method to define arguments when there are less number of arguments to a closure or they are faily simple values, Otherwise code can get pretty confusing to read.

Next we will learn about Trailing Closures