我有一本定义如下的字典
@State var instructorNamesDictionary: [String: [String]] = [:]
稍后将内容添加到 .task 中的字典中
for course in courses{
var updatedinstructors: [InstructorModel] = []
for instructorID in course.instructors {
let instructor = try await getInstructor(uid: instructorID)
updatedinstructors.append(contentsOf: instructor)
for names in updatedinstructors{
instructorNamesDictionary[instructorID] = [names.name]
}
}
}
之后,我尝试将此字典使用到一个名为 CourseCard 的结构中,该结构接受一些参数:
struct CoursesCard: View {
var name: String
var image: Image
var youtubeLinks: [String]
var description: String
var instructors: [String]
var labels: [String]
var isFree: Bool
var ispro: Bool
//rest of design code
}
现在当我在另一个数组上执行 ForEach 循环时
ForEach(basicCourses){course in
let image = images[course.image_ref] ?? Image("noImage")
CoursesCard(name: course.Name, image: image, youtubeLinks: course.youtube_videos, description: course.Description, instructors: instructorNamesDictionary[
ForEach(course.instructors){instruc in
instruc}] ?? ["No instructor"], labels: course.labels, isFree: course.isfree, ispro: isPro)
这给了我“无法将类型‘[CourseModel]’的值‘basicCourses’转换为预期类型‘Binding<[CourseModel]>’,请改用包装器”
但是,如果我传递另一个数组,则不会给出错误。
如果需要,这里是 CourseModel 和 InstructorModel:
struct CourseModel: Decodable,Identifiable {
let id: String
let Name: String
let Description: String
let image_ref: String
let youtube_videos: [String]
let labels: [String]
let instructors: [String]
let isfree: Bool
enum CodingKeys: String, CodingKey {
case id
case Name
case Description
case image_ref
case youtube_videos
case labels
case instructors
case isfree
}
}
struct InstructorModel: Decodable,Identifiable {
let id: String
let name: String
enum CodingKeys: String, CodingKey {
case id
case name
}
}
我尝试将 ForEach 循环更改为
ForEach($basicCourses){$course in
let image = images[course.image_ref] ?? Image("noImage")
CoursesCard(name: course.Name, image: image, youtubeLinks: course.youtube_videos, description: course.Description, instructors: instructorNamesDictionary[
ForEach(course.instructors){instruc in
instruc}] ?? ["No instructor"], labels: course.labels, isFree: course.isfree, ispro: isPro)
但这只会抛出其他错误。
您应该在
CoursesCard
初始值设定项之外提取讲师姓名,并将它们作为字符串数组传递。
ForEach(basicCourses) { course in
let image = images[course.image_ref] ?? Image("noImage")
let instructorNames = course.instructors.compactMap { instructorID in
instructorNamesDictionary[instructorID]?.first ?? "No Instructor"
}
CoursesCard(
name: course.Name,
image: image,
youtubeLinks: course.youtube_videos,
description: course.Description,
instructors: instructorNames,
labels: course.labels,
isFree: course.isfree,
ispro: isPro
)
}