J.Doe
J.Doe

Reputation: 1137

How to find the index of an item in an array of class in Swift?

Well first of all we all know that finding an index of an array is easy but I got stump finding an index of an item in an array which contains multiple structs.

This is my class:

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
    }
}

This is my array:

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})
        }

So pSample is initially a blank array and it appends a class of items through a loop.

The sortInPlace function helps me to sort pSample based on globalPatientMilaAge.

So this got me thinking, how do I get the index of my AppUserID(which I cast it as a String) from the array of class?

I tried using this function but it doesn't seems working because I'm looping through classes instead of items inside a class.

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

Upvotes: 1

Views: 4440

Answers (3)

Krishna Kumar Thakur
Krishna Kumar Thakur

Reputation: 1476

In Swift 3 and above mapping works like this

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

Upvotes: 1

vadian
vadian

Reputation: 285079

The body of indexOf can be a closure like the map and filter functions

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

PS: It's pretty inefficient to get one object from json (json[0][i]) 6 times in the repeat loop.
Assign the object to a variable

let object = json[0][i]

and use it for example

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

Upvotes: 5

Venk
Venk

Reputation: 5955

Do like this,

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

Upvotes: 1

Related Questions