【问题标题】:How to find the index of an item in an array of class in Swift?如何在 Swift 中的类数组中查找项目的索引?
【发布时间】:2016-02-02 05:37:42
【问题描述】:

首先我们都知道查找数组的索引很容易,但我很难在包含多个结构的数组中查找项目的索引。

这是我的课:

class Patient{
private var id: Int
private var name: String
private var gender: String
private var mileage: Double

//global variable
var globalPatientID:Int{
    return id
}
var globalPatientName:String{
    return name
}
var globalPatientGender:String{
    return gender
}
var globalPatientMileAge:Double{
    return mileage
}

init(id:Int, name:String, gender:String, mileage:Double){
    self.id = id
    self.name = name
    self.gender = gender
    self.mileage = mileage
    }
}

这是我的数组:

let AppUserID = prefs.objectForKey("AppUserID")

        for var i=0; i<nou; ++i{
            numberOfUsersExisting = nou

            if (AppUserID as? String == json[0][i]["App_ID"].stringValue){
                print("Assigning AppUserID")
                appUserMileage = json[0][i]["Mileage"].doubleValue
            }

            pSample += [Patient(id: json[0][i]["ID"].intValue, name: json[0][i]["Name"].stringValue, gender: json[0][i]["Gender"].stringValue, mileage: json[0][i]["Mileage"].doubleValue)]

            pSample.sortInPlace({$0.globalPatientMileAge < $1.globalPatientMileAge})
        }

所以 pSample 最初是一个空白数组,它通过循环附加一类项目。

sortInPlace 函数帮助我根据 globalPatientMilaAge 对 pSample 进行排序。

所以这让我开始思考,如何从类数组中获取我的 AppUserID(我将其转换为字符串)的索引?

我尝试使用此函数,但它似乎不起作用,因为我正在循环遍历类而不是类中的项目。

appUserRanking = pSample.indexOf("\(AppUserID)")

【问题讨论】:

  • 私有和公共属性的目的是什么?如果您想拥有只读属性,只需将属性声明为常量。
  • 为了将来参考,现在的问题是如何从结构数组中获取索引...

标签: ios arrays swift swift2


【解决方案1】:

indexOf 的主体可以是像 mapfilter 函数这样的闭包

appUserRanking = pSample.indexOf{$0.globalPatientID == AppUserID}

PS:在重复循环中从 json (json[0][i]) 获取一个对象 6 次是非常低效的。
将对象分配给变量

let object = json[0][i]

并以它为例

if (AppUserID as? String == object["App_ID"].stringValue){

【讨论】:

  • 是的,仅仅为了得到一个对象而循环确实是非常不够的,所以我实际上在循环之后使用了这个函数,它做得很好。
【解决方案2】:

这样做,

let pSampleFiltered = pSample.filter {$0.globalPatientID == AppUserID}
if pSampleFiltered.count > 0 {
   if let index = pSample.indexOf(pSampleFiltered.first!) {
      // Do your stuff here
   }
}

【讨论】:

  • 过滤整个列表效率不高。带有闭包参数的 indexOf 是更好的解决方案。
【解决方案3】:

在 Swift 3 及更高版本中,映射的工作方式是这样的

appUserRanking  = pSample.index(where: {$0.globalPatientID == AppUserID})

【讨论】:

    猜你喜欢
    • 2020-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-10
    • 2018-11-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多