You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

能否用willSet构造类实例的字典条目?(Xcode9.2、Swift4.1环境)

使用willSet实现字典条目的创建与更新

当然可以!用Swift的属性观察器willSet完全能实现你要的字典条目创建与更新逻辑,甚至能让代码更简洁直观~

先回顾下你原来的set方法逻辑:每次调用时会检查properties字典里是否存在对应key的Prop实例——不存在就新建一个存入字典,存在则直接更新它的origin属性。下面是用willSet实现的方案:

完整实现代码

class Prop : Codable {
    var origin: String?
    var result: String?
    
    init(_ origin: String) {
        self.origin = origin
    }
}

class PropList : Codable {
    var properties = [String: Prop]()
    
    // 定义辅助属性,通过willSet处理创建/更新逻辑
    var updateProperty: (key: String, origin: String)? {
        willSet {
            guard let newUpdate = newValue else { return }
            let targetKey = newUpdate.key
            let newOrigin = newUpdate.origin
            
            if let existingProp = properties[targetKey] {
                // 条目已存在,更新origin
                existingProp.origin = newOrigin
            } else {
                // 条目不存在,创建新实例存入字典
                properties[targetKey] = Prop(newOrigin)
            }
        }
    }
    
    // 定义CodingKeys,排除updateProperty避免被编码/解码
    enum CodingKeys: String, CodingKey {
        case properties
    }
}

使用示例

let propList = PropList()

// 创建新条目
propList.updateProperty = ("username", "initial_user")
print(propList.properties["username"]?.origin) // 输出: Optional("initial_user")

// 更新已有条目
propList.updateProperty = ("username", "updated_user")
print(propList.properties["username"]?.origin) // 输出: Optional("updated_user")

说明

  • 我们通过一个可选元组属性updateProperty的willSet观察器,把原来set方法的逻辑封装了起来,每次给这个属性赋值时,就会自动触发创建或更新操作。
  • 因为updateProperty只是辅助操作属性,不需要参与Codable的编码/解码,所以我们定义了CodingKeys枚举来排除它,保证原有的Codable功能不受影响。
  • 这种方式比调用方法更符合Swift的属性式操作风格,代码可读性也更强。

内容的提问来源于stack exchange,提问作者cdeerinck

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:26:13