Pushpendra
Pushpendra

Reputation: 1519

How we can find an element from [AnyObject] type array in swift

I have [AnyObject] array

var updatedPos = [AnyObject]()

I am setting data in that according to my requirement like!

let para:NSMutableDictionary = NSMutableDictionary()
para.setValue(posId, forKey: "id")
para.setValue(posName, forKey: "job")
let jsonData = try! NSJSONSerialization.dataWithJSONObject(para, options: NSJSONWritingOptions())
let jsonString = NSString(data: jsonData, encoding: NSUTF8StringEncoding) as! String
self.updatedPos.append(jsonString)

Now in my code i have some requirement to remove the object from this array where id getting matched according to requirement Here is the code which i am trying to implement

for var i = 0; i < updatedPos.count; i++
        {
            let posItem = updatedPos[i]
            print("Id=\(posItem)")
            let pId = posItem["id"] as? String
            print("secRId=\(pId)")
            
            if removeId! == pId!
            {
                updatedPos.removeAtIndex(i)
            }
        }

Here print("Id=\(posItem)") give me output asId={"id":"51","job":"Programmer"} but here i am not able to access id from this object. here print("secRId=\(pId)") give me nil

Upvotes: 0

Views: 2294

Answers (2)

Pushpendra
Pushpendra

Reputation: 1519

After some little bit stuffs I have found the very easy and best solution for my question. And I want to do special thanks to @vadian. Because he teach me new thing here. Hey Thank you very much @vadian

Finally the answer is I had covert posItem in json Format for finding the id from Id={"id":"51","job":"Programmer"} this string

And the way is

let data = posItem.dataUsingEncoding(NSASCIIStringEncoding, allowLossyConversion: false)
   do {
        let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)
        if let dict = json as? [String: AnyObject] {
           let id = dict["id"]
           if removeId! == id! as! String
             {
               updatedLoc.removeAtIndex(i)
             }        
          }
       }
     catch {
        print(error)
     }

Upvotes: 0

vadian
vadian

Reputation: 285082

  • First of all use native Swift collection types.
  • Second of all use types as specific as possible.

For example your [AnyObject] array can be also declared as an array of dictionaries [[String:AnyObject]]

var updatedPos = [[String:AnyObject]]()

Now create the dictionaries and add them to the array (in your example the dictionary is actually [String:String] but I keep the AnyObject values).

let para1 : [String:AnyObject] = ["id" : "51", "job" : "Programmer"]
let para2 : [String:AnyObject] = ["id" : "12", "job" : "Designer"]
updatedPos.append(para1)
updatedPos.append(para2)

If you want to remove an item by id use the filter function

let removeId = "12"
updatedPos = updatedPos.filter { $0["id"] as? String != removeId  }

or alternatively

if let indexToDelete = updatedPos.indexOf{ $0["id"] as? String == removeId} {
   updatedPos.removeAtIndex(indexToDelete)
}

The JSON serialization is not needed for the code you provided.

PS: Never write valueForKey: and setValue:forKey: unless you know exactly what it's doing.

Upvotes: 1

Related Questions