Search code examples
swiftnullreference-type

Set multiple reference type values to nil at once


Suppose that I have an array of UIView?s that have a value by default:

var firstView: UIView? = UIView()
var secondView: UIView? = UIView()
let views = [firstView, secondView]

I want to change every value that's in the array to nil. The ideal solution would be iterating through the elements of the array and setting them to nil. However, this does not work:

print(firstView) //Optional(<UIView: [address]; frame = (0 0; 0 0); layer = <CALayer: [address]>>)

for i in 0 ..< views.count {
    views[i] = nil
}

//firstView is still not nil
print(firstView) //Optional(<UIView: [address]; frame = (0 0; 0 0); layer = <CALayer: [address]>>)

What could be the solution for this?


Solution

  • As MartinR said in this comment, it's not possible to directly modify the address of an instance variable. Some possible solutions for this problem:

    • As MartinR points out, you can store the views only in that array and nowhere else. That way, when you make every element in your array nil, there won't be any references for the views. However, this can easily produce an overly long or hard-to-understand code.
    • A usually better solution for UIViews is creating a custom view and put all elements in it that you'd store in an array otherwise. That way, you can easily make that one view nil and all subviews will be nil (since they rely on the superview).