你可以用
KeyPath
S:
class Foo {
let views = [\Foo.view1, \Foo.view2]
var view1: UIView? = UIView()
var view2: UIView? = UIView()
func freeAll() {
print(view1 as Any, view2 as Any)
for keyPath in views {
self[keyPath: keyPath] = nil
}
print(view1 as Any, view2 as Any)
}
}
let foo = Foo()
foo.freeAll()
输出:
Optional(<UIView: 0x7fc5c4107bb0; frame = (0 0; 0 0); layer = <CALayer: 0x60000213e760>>) Optional(<UIView: 0x7fc5c41057a0; frame = (0 0; 0 0); layer = <CALayer: 0x60000213d780>>)
nil nil
在这种情况下,
views
数组不包含对对象的引用,而是存储
关键路径
你可以把它看作是如何找到它们的方向。允许您访问对象并将其设置为
nil
如果需要。