Swift - 在 map 中存储值。结构与类中的不同行为

标签 swift

如果将 SomeClass 定义为结构,则此示例 Swift 代码无法编译。编译器说:@value $T6 与 (String, Proto) 不同

但是,如果 SomeClass 是一个类,编译器不会报错。

为什么?


public protocol Proto {
    func hello(value:Int)
}


public struct SomeClass {

    var map = [String:Proto]()

    public func store (key:String, value:Proto) {

        map[key] = value // That does not work if SomeClass is a struct  

    }
}


最佳答案

因为你在store函数中修改了struct的元素,如果你这样做,你必须给它加上“mutating”前缀。 所以:

public mutating func store (key:String, value:Proto) {

    map[key] = value // That does not work if SomeClass is a struct

}

Structures and enumerations are value types. By default, the properties of a value type cannot be modified from within its instance methods.

However, if you need to modify the properties of your structure or enumeration within a particular method, you can opt in to mutating behavior for that method.

关于Swift - 在 map 中存储值。结构与类中的不同行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28148731/

相关文章:

swift - 有没有办法快速连接 var 的名称?

swift - 渲染现有参与者的视频轨道

swift - Rx swift : how to build up the observable function call chain other than use callback?

arrays - swift:扩展数组的可比性

swift - Swift-在MKCircle中设置多个fillColor

ios - 在 alamofire 闭包中从自定义框架传回数组

ios - 如何将 segue 连接到不是第一个单元格的单元格上的披露指示器?

ios - 在 api 类之外显示与 alamofire 相关的警报

ios - App Store 提交的最低 Xcode/swift 版本

快速 uipickerview 高度更改不起作用