Posts Boring guide to Closures in Swift - Closure Expression Syntax
Post
Cancel

Boring guide to Closures in Swift - Closure Expression Syntax

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

1
2
3
{ (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:

1
2
3
4
5
6
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:

1
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.

1
2
3
4
5
6
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.

1
2
3
4
5
6
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

This post is licensed under CC BY 4.0 by the author.

Contents

Trending Tags