我有一个包含student objects
的数组和另一个包含goodStrudentId
的数组。我需要按照students
的顺序从goodStrudentId
数组中获取所有学生对象。
使用多个forloop我可以解决这个问题,但我想学习解决这个问题的最佳方法。我唯一的问题是遵循goodStrudentId
的顺序。
以下是了解我的问题的示例代码 -
class Student {
var s_id : String
var s_name : String
init(i: String, n: String) {
self.s_id = i;
self.s_name = n;
}
}
var students = [Student(i: "1",n: "a"),
Student(i: "2",n: "b"),
Student(i: "3",n: "c"),
Student(i: "4",n: "d"),
Student(i: "5",n: "e")]
var goodStudentsId = ["5","2"]
var goodStudentObject = getGoodStudentObjectUsingId(students:students, gdStudentsId:goodStudentsId)
/*
Expected answer:
var goodStudentObject = [Student(i: "5",n: "e"), Student(i: "2",n: "b")]
*/
func getGoodStudentObjectUsingId(students:Array<Student>, gdStudentsId:Array<String>) -> Array<Student>! {
/*?????? please complete this func*/
return [];
}
答案 0 :(得分:1)
func getGoodStudentObjectUsingId(students:[Student], gdStudentsId:[String]) -> [Student] {
return students.filter {
gdStudentsId.contains($0.s_id)
}
}