我有一个 SwiftData 模型,最近添加了一个新数组,该数组以字符串形式保存“Sections”。无论我尝试什么,我都无法让 Swift 使用 ForEach、For 或 List 以任何方式遍历这个数组。我总是收到此错误:
Generic parameter 'V' could not be inferred
如果我使用另一个数组 tapas.asanas,它可以完美运行。
这是代码片段,错误显示在 Section("Sections") 行。
Section("Sections") {
TextField("Add a new Section", text: $sectionName)
.padding([.top, .bottom], 10)
Button(action: {
tapas.tapasSections.append(sectionName)
sectionName = ""
}, label: {
Text("Add Section")
})
List(tapas.tapasSections) { name in
Text("\(name)")
}
}
以下是 SwiftData 模型:
import Foundation
import SwiftData
@Model
class Tapas {
var name: String
/// Time Frame of the Tapas
var currentDay: Int
var lengthInDays: Int = 21
var lastDay: Date
var startDay: Date = Date()
var intention: String
var intentionEvoked: Bool = false
var rules: String = ""
var supportTime: [Date] = []
var tapasSections: [String] = []
var recuperated: Bool
var tapasType: String
var isActive: String
var recupType: String /// NoRecoup, TimedRecoup, UnlimitedRecoup for No recouperations, Recouperations before Last Day, And even after
var resetTime: Date
var color: String
/// Adding a relation to TapasAsana, as one Tapas has many Asanas
@Relationship(deleteRule: .cascade) var asanas = [TapasAsana]()
init(name: String = "", intention: String = "", currentDay: Int = 1, lengthInDays: Int = 49, lastDay: Date = .now, recuperated: Bool = false, tapasType: String = "hatha", isActive: String = "dormant", recupType: String = "NoRecoup", resetTime: Date = .now, color: String = "blue") {
self.name = name
self.intention = intention
self.currentDay = currentDay
self.lengthInDays = lengthInDays
self.lastDay = lastDay
self.recuperated = recuperated
self.tapasType = tapasType
self.isActive = isActive
self.recupType = recupType
self.resetTime = resetTime
self.color = color
}
}
正如我之前所说,这个名为 asanas 的关系数组可以在任何 ForEach 或 List 中工作,在上面的代码中也是如此。用 tapas.tapasSections 替换 tapas.tapasSections 可以解决错误。
之所以无法编译,是因为事实上
String
无法编译,Identifiable
但是您所使用的初始化程序List
需要编译。这里有两种可能的解决方案:
使
String
符合Identifiable
使用不同的初始化程序
List
tapas.tapasSections
用进行替换tapas.asanas
是可行的,因为@Model
包装器使TapasAsana
类符合 ,PersistentModel
从而使其符合Identifiable
。文档