首先,我们都知道找到数组的索引很容易,但我很难在包含多个结构的数组中找到一个项目的索引。
这是我的课:
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)")
最佳答案
indexOf
的主体可以像 map
和 filter
函数一样是一个闭包
appUserRanking = pSample.indexOf{$0.globalPatientID == AppUserID}
PS:重复循环6次从json(json[0][i]
)中获取一个对象是非常低效的。
将对象分配给变量
let object = json[0][i]
并使用它作为例子
if (AppUserID as? String == object["App_ID"].stringValue){
关于ios - 如何在 Swift 的类数组中查找项目的索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35145847/