如果将 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/