在列表中遍历一组已选中的项时遇到困难

移动开发 2026-07-09

在SwiftUI中,我声明了一个课程列表。我想能够选择多门课程,以便执行某些操作。

我已经声明了一个Course结构体:

struct Course: Identifiable, Hashable {
    let id = UUID() // Generates a unique ID automatically
    var title: String
}

我声明了一个State变量:

@State private var selectedIds = Set<Course>() 

下面是List的 UI代码:

List(courses, id: \.self, selection: $selectedIds) { course in
    Text(course.title)
}

因此这段代码可以工作:

Button("Delete Selected") {
    let arr = Array(arrayLiteral: $selectedIds)
    for c in arr {
        print(c)
    }
}

但这段代码不能编译:

Button("Delete Selected") {
    let arr = Array(arrayLiteral: $selectedIds)
    for c in arr {
        print(c.title)
    }
}

Xcode在编辑器中给出如下错误:

Value of type 'Binding<Set<Course>>' has no dynamic member 'title' using key path from root type 'Set<Course>'

我不明白如何把列表中的元素作为Course对象来访问。我尝试过强制类型转换,但没有成功。

谢谢!

解决方案

首先通过移除 Hashable 和移除 id: \.self 来修正几个错误,然后把选择改成如下:

@State private var selectedIds = Set<Course.ID>()

接着对删除,尝试如下:

struct Course: Identifiable {
    let id = UUID()
    var title: String
}

@State private var selectedIds = Set<Course.ID>()
@Binding var courses: [Course]

func deleteSelectedCourses() {
    // Remove any course whose ID is contained within the selection Set
    // This does loop the whole courses array though but at least it only loops once.
    courses.removeAll { course in
        selectedIds.contains(course.id)
    }

    // Optional: Clear the selection set after a successful deletion
    selectedIds.removeAll()
}
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章