You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift中如何在Student类方法内查找其所属YearGroup的数组索引

方案1:添加反向引用(推荐,性能最优)

当前Student实例默认没有和所属YearGroup的关联逻辑,最合理的方式是给Student加弱引用属性指向所属的YearGroup,避免循环引用:

class YearGroup {
    var id = UUID()
    var students = [Student]()
    var myIndex = 0

    func findMyIndex() {
        myIndex = yeargroups.firstIndex(where: {$0.id == self.id})!
    }
    
    // 新增添加学生的方法,自动绑定所属年级
    func addStudent(_ student: Student) {
        student.yearGroup = self
        students.append(student)
    }
}

class Student {
    let id = UUID()
    var name:String
    var age:Int
    var myYearGroupIndex = 0
    // 新增弱引用属性指向所属年级,避免循环引用
    weak var yearGroup: YearGroup?

    init(n:String, a:Int) {
        name = n
        age = a
    }

    func findMyYearGroupIndex() {
        // 先让所属年级查到自己的索引,再赋值即可
        yearGroup?.findMyIndex()
        myYearGroupIndex = yearGroup?.myIndex ?? 0
        // 如果不想依赖YearGroup的findMyIndex方法,也可以直接查询:
        // if let group = yearGroup {
        //     myYearGroupIndex = yeargroups.firstIndex(where: {$0.id == group.id})!
        // }
    }
}

var yeargroups = [YearGroup]()

该方案无需每次遍历所有年级和学生,查询效率高,逻辑清晰。


方案2:遍历匹配(无需修改现有属性结构)

如果不想调整现有属性结构,可以直接遍历所有年级的学生数组,匹配当前Student的id即可:

func findMyYearGroupIndex() {
    // 遍历所有年级,查找包含当前学生的年级
    for (index, group) in yeargroups.enumerated() {
        if group.students.contains(where: { $0.id == self.id }) {
            myYearGroupIndex = index
            return
        }
    }
    // 未匹配到可自定义默认值,此处示例赋值为0
    myYearGroupIndex = 0
}

该方案每次查询都要遍历所有年级和学生,数据量大的时候性能较差,仅适合小规模数据场景。

内容的提问来源于stack exchange,提问作者Daniel Ardel-Smith

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 16:24:03