【问题标题】:Swift - Get Object in Array By Property [duplicate]Swift - 按属性获取数组中的对象
【发布时间】:2016-05-22 17:38:18
【问题描述】:

我是 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 返回一个对象。有人可以告诉我该怎么做......例如其中 listPose.Id === Id;

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


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

}

【问题讨论】:

标签: arrays xcode swift object collections


【解决方案1】:

所以 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 属性是一个可选对象,您稍后需要解包

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-28
    • 1970-01-01
    • 1970-01-01
    • 2016-01-22
    • 1970-01-01
    • 2022-10-19
    • 1970-01-01
    相关资源
    最近更新 更多