2016-02-11 93 views
3

我是Swift的新手,我在通過屬性檢索數組中的對象時遇到了一些問題。Swift - 通過屬性獲取數組中的對象

請注意,我使用的是Swift 2.0。

我有以下數組;

//Dummy Data prior to database call: 
static var listPoses = [ 
    YogaPose(id: 1, title: "Pose1", description: "This is a Description 1", difficulty: Enums.Difficulty.Beginner, imageURL: "Images/Blah1"), 
    YogaPose(id: 2, title: "Pose2", description: "This is a Description 2", difficulty: Enums.Difficulty.Advanced, imageURL: "Images/Blah2"), 
    YogaPose(id: 3, title: "Pose3", description: "This is a Description 3", difficulty: Enums.Difficulty.Intermediate, imageURL: "Images/Blah3"), 
    YogaPose(id: 3, title: "Hello World", description: "This is a Description 3", difficulty: Enums.Difficulty.Intermediate, imageURL: "Images/Blah3") 
] 

我現在有一個方法,我想通過Id返回一個對象。有人可以告訴我該怎麼做......例如where listPose.Id === Id;

//Returns a single YogaPose By Id: 
class func GetPosesById(Id: Int) -> YogaPose{ 


    if(listPoses.count > 0){ 
     return listPoses() ... 
    } 

} 
+0

或者這一個:在數組中找到一個對象?](http://stackoverflow.com/questions/28727845/find-an-object-in-array)。 –

回答

9

因此,Swift提供了一種基於所需條件篩選對象列表的方法。

在這種情況下,您將需要使用filter功能:

class func GetPosesById(Id: Int) -> YogaPose?{ 
    return listPoses.filter({ $0.id == Id }).first 
} 

基本上,filter功能將環通整個listPoses並返回你[YogaPose]。代碼({$0.id == Id})是您的條件,$0表示循環中的當前對象。

我也改變你的函數簽名有點

class func GetPosesById(Id: Int) -> YogaPose 

class func GetPosesById(Id: Int) -> YogaPose? 

因爲first屬性是一個可選的對象,你以後需要解開