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() ...
}
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With