【问题标题】:Swift3 - Issue with extending type CollectionSwift3 - 扩展类型集合的问题
【发布时间】:2017-02-11 10:40:34
【问题描述】:

早安,

我试图理解 Swift 3 中的协议和扩展。

我试图通过可变函数将Collection 扩展为例如治疗 Enemy 类型数组内的所有敌人。

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

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

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

最好的祝愿,祝你有美好的一天,

流水

【问题讨论】:

    标签: arrays swift collections protocols swift-playground


    【解决方案1】:

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

    【讨论】:

    • 你是对的。我完全忘记了结构是按值传递的。谢谢。
    • 没问题:)如果有帮助请接受答案:)
    猜你喜欢
    • 1970-01-01
    • 2013-08-25
    • 2011-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-22
    • 2011-05-02
    相关资源
    最近更新 更多