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存储枚举值。
