你好,
我试图理解 Swift 3 中的协议(protocol)和扩展。
我正在尝试通过可变函数扩展 Collection
,例如治疗 Enemy
类型数组中的所有敌人。
这是一个 GIST 示例:https://gist.github.com/flowinho/5985928f803d902b75fc69ee9ce26537
我对通过扩展协议(protocol)添加可变函数的领域还是个新手,所以我不明白为什么那个要点的 LOC 75 不会增加所有敌人的生命值。
我做错了什么? 如何解决这个问题?
祝你有美好的一天,
流动性
最佳答案
这是因为struct是一个值类型,当你赋值的时候会生成一个副本。如果您使用类而不是结构,您的代码将有效。或者您需要通过索引访问数组元素:
for item in myStructArray {
// changes copy of item, array is not altered
item.property = newValue
}
for i in 0..<myStructArray.count {
// this does what you need, changes the struct in the array
myStructArray[i].property = newValue
}
关于arrays - Swift3 - 扩展类型 Collection 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42174898/