Sobes.tech
Junior — Senior

What will be output when using unowned in a closure?

livecode

Task condition

In this Swift example, it shows how a closure captures a UIView object with unowned. First, a UIView object is created, assigned a tag of 1, and then the closure prints the tag value. Then, the variable is assigned a new UIView object with a tag of 2, and the closure is called again. It is necessary to understand what value will be printed each time.

var container = UIView()
container.tag = 1

let displayTag = { [unowned container] in
    print(container.tag)
}

displayTag()

container = UIView()
container.tag = 2

displayTag()