我有一個數組student objects
和另一個數組goodStrudentId
。我需要按照goodStrudentId
的順序從students
數組中獲取所有學生對象。 使用多個forloop我可以解決這個問題,但我想學習解決這個問題的最佳方法。我唯一的問題是按照goodStrudentId
的順序。 下面是一個示例代碼來了解我的問題 -Swift:過濾數組的最佳方法
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 [];
}
陣列具有'filter'功能;在谷歌搜索這個問題之後,這應該很清楚。你嘗試了什麼? – Connor
這個網站是一個很好的教育資源,用於更高級的swift函數:https://www.weheartswift.com/higher-order-functions-map-filter-reduce-and-more/ – toddg
我試過用NSPredicate。我會嘗試以下答案..不知道爲什麼我得到反對票。 – Shohrab