gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 13:17:59 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com