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

如何在自定义Codable类型上使用@AppStorage解决初始化器匹配错误

解决@AppStorage存储自定义[NameSection]数组报错问题

原因

@AppStorage默认只支持String、Int、Bool等基础类型,自定义类型需要自行实现适配逻辑,你已经为NameSection、NameItem实现了Codable协议,可以直接通过扩展AppStorage实现通用适配。

解决步骤

步骤1:添加AppStorage通用扩展

将以下代码添加到你的项目公共代码区域,可适配所有遵循Codable协议的类型:

import SwiftUI

extension AppStorage where Value: Codable {
    init(wrappedValue: Value, _ key: String, store: UserDefaults? = nil) {
        let decoder = JSONDecoder()
        let encoder = JSONEncoder()
        
        self.init(
            key,
            store: store,
            get: { defaults in
                guard let data = defaults.data(forKey: key) else {
                    return wrappedValue
                }
                return (try? decoder.decode(Value.self, from: data)) ?? wrappedValue
            },
            set: { newValue, defaults in
                guard let data = try? encoder.encode(newValue) else {
                    return
                }
                defaults.set(data, forKey: key)
            }
        )
    }
}

步骤2:修正属性声明

给你的name属性添加默认值即可正常使用:

@AppStorage("imports") var name: [NameSection] = []

效果说明

你现有的文件导入解码逻辑无需修改,解码后直接给name赋值就会自动触发持久化存储,应用下次启动时会自动读取AppStorage中已保存的数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.18 11:15:01