xcode Swift - 按属性获取数组中的对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35347900/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Swift - Get Object in Array By Property
提问by japes Sophey
I'm new to Swift and I am having a few problems with retrieving an object in an array by property.
我是 Swift 的新手,在按属性检索数组中的对象时遇到了一些问题。
Please note, I am using Swift 2.0.
请注意,我使用的是 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;
我现在有一个方法,我想通过 Id 返回一个对象。有人可以建议我怎么做吗……例如,listPose.Id === Id;
//Returns a single YogaPose By Id:
class func GetPosesById(Id: Int) -> YogaPose{
if(listPoses.count > 0){
return listPoses() ...
}
}
回答by Breek
So Swift provides your a way to filter a list of object based on the condition you want.
因此,Swift 提供了一种根据您想要的条件过滤对象列表的方法。
In this case, you will need to use filter
function:
在这种情况下,您将需要使用filter
函数:
class func GetPosesById(Id: Int) -> YogaPose?{
return listPoses.filter({ class func GetPosesById(Id: Int) -> YogaPose
.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.
基本上,该filter
函数将遍历整个listPoses
并返回一个[YogaPose]
. 代码({$0.id == Id})
是您的条件,$0
表示循环中的当前对象。
I also change your function signature a bit
我也稍微改变了你的函数签名
class func GetPosesById(Id: Int) -> YogaPose?
To
到
##代码##because the first
property is an optional object which you will need to unwrap later
因为该first
属性是一个可选对象,您稍后需要解开它