SwiftData新增枚举类型报错
SwiftData新增枚举类型报错

SwiftData新增枚举类型报错

SwiftData新增枚举类型:

@Model
class SavingsRecord {
    var amount: Double = 0.0
    var date: Date = Date()
    var saveMoney: Bool = false
    var note: String? = nil
    var type: SavingsRecordType = SavingsRecordType.manual  // 新增枚举
}

Xcode报错:

/var/folders/1y/t7s8thm536j0hgvd3fhdp7pr0000gn/T/swift-generated-sources/@__swiftmacro_6piglet13SavingsRecordC4type18_PersistedPropertyfMa_.swift:4:23 No exact matches in call to instance method 'setValue'
/var/folders/1y/t7s8thm536j0hgvd3fhdp7pr0000gn/T/swift-generated-sources/@__swiftmacro_6piglet13SavingsRecordC4type18_PersistedPropertyfMa_.swift:9:21 No exact matches in call to instance method 'getValue'
/var/folders/1y/t7s8thm536j0hgvd3fhdp7pr0000gn/T/swift-generated-sources/@__swiftmacro_6piglet13SavingsRecordC4type18_PersistedPropertyfMa_.swift:13:18 No exact matches in call to instance method 'setValue'

SwiftData要求自定义类型必须符合可持久化协议,而枚举必须满足以下条件:

1、枚举必须Codable

2、枚举必须RawRepresentable,并且RawValue是SwiftData支持的基础类型(如String、Int)。

解决方案:

enum SavingsRecordType: String,Identifiable {
    var id: String {
        self.rawValue
    }
    case manual     // 用户手动存/取
    case automatic  // 系统按频率自动执行的定期存款
}

@Model
class SavingsRecord {
    var amount: Double = 0.0
    var date: Date = Date()
    var saveMoney: Bool = false
    var note: String? = nil
    var type: String = SavingsRecordType.manual.rawValue  // 新增枚举
}

将枚举类型改为String或Int类型,枚举遵循String或Int协议,使用rawValue存储枚举值。

   

如果您认为这篇文章给您带来了帮助,您可以在此通过支付宝或者微信打赏网站开发者。

欢迎加入我们的 微信交流群QQ交流群,交流更多精彩内容!
微信交流群二维码 QQ交流群二维码

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注