Swift3 - 扩展类型 Collection 的问题

Swift3 - Issue with extending type Collection

美好的一天,

我正在尝试了解 Swift 3.

中的协议和扩展

我正在尝试通过可变函数扩展 Collection,例如治疗 Enemy.

类型阵列中的所有敌人

这是一个 GIST 示例:https://gist.github.com/flowinho/5985928f803d902b75fc69ee9ce26537

我对通过扩展协议添加可变函数的领域还很陌生,所以我不明白为什么那个要点的 LOC 75 不会增加所有敌人的生命值。

我做错了什么? 如何解决这个问题?

祝你有美好的一天,

Flowinho

这是因为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
}