逻辑是当一个数组有指定数量的元素时清除它。我可以将检查放在数组之外,但我想看看如果在数组的 willSet 事件中执行它会怎样。结果是 Array 中的元素保持静止。
这是代码
var MyArr=[String]() {
willSet{
print("now count is:\(MyArr.count)")
if MyArr.count>2 {
print("now remove all!")
MyArr.removeAll()
}
}
}
MyArr.append("hello")
MyArr.append(",world")
MyArr.append("!")
MyArr.append("too much.")
print("The conent is \(MyArr)")
MyArr 预计只有一个元素,而实际结果是四个。
最佳答案
该行为与值类型/引用类型无关
请注意警告
Attempting to store to property 'MyArr' within its own willSet, which is about to be overwritten by the new value
这意味着修改willSet
中的对象没有效果。
关于arrays - 为什么我不能在其 willSet 事件中从数组中删除元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51481607/