Closure Trick in Swift

Today I learned a closure trick in Swift. Usually when expression is assigned to a variable on left, it is evaluated instantly.

For example,

let value = complexCalculation()

func complexCalculation() -> String {
    return "Something useful"
}

In this example, when value is assigned a result of complexCalculation() method, it is called immediately. However, there is an alternative (Not necessarily better) way to handle this kind of situation where evaluating an expression can be deferred until explicit requirement.

In this case, you can wrap the expression (Whose execution you want to defer until later) in the curly braces.

// result is a closure of type () -> String which can then be evaluated. But complexCalculation() won't be called until executed manually.
let result = { self.complexCalculation() }

// Following line will take a closure result and call it to get return value as Something useful

// Will print "Something useful"
print(result())

This is not a great trick as per say, but I found it interesting that Swift allows to convert expression into closure by wrapping it into curly braces. Please note that when inside closure, you will have to follow all the rules of closure expression. If you are calling an instance method inside closure, make sure to use explicit self before making the call