Closures Are Reference Types

Chapter 4, “Structuring Code: Enums, Structs, and Classes,” talks about reference types and value types. It talks about the difference between things being copied versus being referenced when they are passed around. If you think about it, it makes a lot of sense for closures to be reference types rather than value types. Closures capture values in their context. If a closure were copied every time it was passed around, it would lose context that it has access to. In other words, it would lose access to those local variables. Here’s an example:

func increment(n:Int)-> ()->Int {    var i = 0    var incrementByN = {        () -> Int in        i += n        return i    }    return incrementByN ...

Get Learning Swift™ Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.