Swift - 按属性获取数组中的对象

jap*_*hey 3 arrays collections xcode object 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")
] 
Run Code Online (Sandbox Code Playgroud)

我现在有一个方法,我想通过Id返回一个对象.有人可以建议我怎么做...例如listPose.Id === Id;

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


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

}
Run Code Online (Sandbox Code Playgroud)

Bre*_*eek 12

因此,Swift提供了一种根据所需条件过滤对象列表的方法.

在这种情况下,您将需要使用filter功能:

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

基本上,该filter函数将循环通过整个listPoses并返回一个[YogaPose].代码({$0.id == Id})是你的条件,$0意味着循环中的当前对象.

我也稍微改变了你的功能签名

class func GetPosesById(Id: Int) -> YogaPose
Run Code Online (Sandbox Code Playgroud)

class func GetPosesById(Id: Int) -> YogaPose?
Run Code Online (Sandbox Code Playgroud)

因为该first属性是一个可选对象,您需要稍后解包