Search code examples
swiftfunctionsyntaxclosures

Closure inside function / need explanation


I'm studying closures and saw a unknown (for me) example of the use of closures in function in the book:

func counter() -> () -> Int {
    var count = 0
    let incrementer: () -> Int = {
        count += 1
        return count
    }
    return incrementer
}

But I've never seen such a way of creating a closure. I've tried the usual one method and that worked too:

func counter() -> Int {
    var count = 0
    let incrementer = { () -> Int in
        count += 1
        return count
    }
    return incrementer()
}

How does it work? Is it just a type annotation?


Solution

  • Both provided functions are counters and you can write this using either counter()() or counter(). They appear to be the same, at first, but you will find that you cannot use counter() more than once because it has only one value, 1, meaning that you used unnecessary steps to make a basic Int var. However, on the other hand, you have counter()(), which counts up like a function after defining an owner pointer via the var keyword.

    So, one defines, uses and deallocates a closure, while the other defines a closure and returns it allowing for reuse.