John Doe
John Doe

Reputation: 55

Saving more than one value to a Dictionary key in a loop with an Array

I have this block of code

//start of the loop
if let objects = objects as? [PFObject] {
    for object in objects {
        //saving the object
        self.likerNames.setObject(object["fromUserName"]!, forKey: saveStatusId!)
   }
}

likerNames is an NSMutableArray declared earlier, saveStatusId is a string I also declared and saved earlier (It's just an objectId as a String), and object["fromUserName"] is an object returned from my query (not shown above).

Everything is working fine as it is but my query sometimes returns more than one object["fromUserName"] to the same key which is saveStatusId. When this happens the value I have for that saveStatusId is replaced when I actually want it to be added to the key.

So want it to kind of look like this

("jKd98jDF" : {"Joe", "John"})
("ksd6fsFs" : {"Sarah"})
("payqw324" : {"Chris", "Sarah", "John"})

I know you can use Arrays but I'm not sure how I would go about that to get it to work in my current situation.

So my question would be how to I get my key (saveStatusId) to store more than one value of object["fromUserName"]?

Upvotes: 2

Views: 278

Answers (1)

nielsbot
nielsbot

Reputation: 16031

Something like this could work

let key = saveStatusId!
let oldValue = self.likerNames.objectForKey( key ) as? [String]
let newValue = (oldValue ?? []) + [ object["fromUserName" ] ]
self.likerNames.setObject( newValue, forKey: key )

If likerNames has an array in slot[saveStatusId], append the new value, otherwise create an array and put that in the right slot

Upvotes: 1

Related Questions