4

I'm new to Swift and I am having a few problems with retrieving an object in an array by property.

Please note, I am using Swift 2.0.

I have the following array;

//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")
] 

I now have a method that I'd like to return an object by Id. Can someone please advise how I would do so ... e.g. where listPose.Id === Id;

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


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

}
1

1 Answer 1

13

So Swift provides your a way to filter a list of object based on the condition you want.

In this case, you will need to use filter function:

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

Basically, the filter function will loop thru the entire listPoses and returns you a [YogaPose]. The code ({$0.id == Id}) is your condition and $0 means the current object in the loop.

I also change your function signature a bit

class func GetPosesById(Id: Int) -> YogaPose

To

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

because the first property is an optional object which you will need to unwrap later

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.