2016-12-22 59 views
-5

我有一個數組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 []; 
} 
+7

陣列具有'filter'功能;在谷歌搜索這個問題之後,這應該很清楚。你嘗試了什麼? – Connor

+0

這個網站是一個很好的教育資源,用於更高級的swift函數:https://www.weheartswift.com/higher-order-functions-map-filter-reduce-and-more/ – toddg

+0

我試過用NSPredicate。我會嘗試以下答案..不知道爲什麼我得到反對票。 – Shohrab

回答

1
func getGoodStudentObjectUsingId(students:[Student], gdStudentsId:[String]) -> [Student] { 
    return students.filter { 
     gdStudentsId.contains($0.s_id) 
    } 
} 
+1

這將按照原始數組中的順序返回學生。從問題中的「預期輸出」中,我假定結果應該根據gdStudentsId中的id進行排序。我當然可能錯了。 –

+0

你能幫我提供客觀的c代碼嗎? – Shohrab

+0

我用快速嘗試。它按預期得到錯誤的順序 – Shohrab

相關問題