我有一个SwiftData模型,最近添加了一个新的数组,它将“Sections”作为字符串保存。无论我尝试什么,我都无法使用ForEach、For或List让Swift以任何方式通过这个数组。我总是会遇到这个错误:
Generic parameter 'V' could not be inferred
如果我使用另一个Array 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.asanas可以解决此错误。