2

I am trying to pass swift array of dictionaries to the NSMutableArray. But I am getting error "Cannot convert value of type [[String : Anyobject?]] to expected argument type NSMutableArray". Below is the code:

   var ary : [[String:AnyObject?]] = []
   var mutableDictionary = [String: AnyObject?]()

   for c in buffer {
       mutableDictionary.updateValue(c.Name, forKey: "name")
       mutableDictionary.updateValue(c.Number, forKey: "phoneNumber")
       mutableDictionary.updateValue(c.id, forKey: "id")
       ary.append(mutableDictionary)
   }

Now passing this "ary" to the Objective C method as a NSMutableArray!

Manager.sharedInstance().List(ary)
4
  • Try Manager.sharedInstance().List(ary as! NSMutableArray). Commented Sep 7, 2016 at 6:15
  • No it crashes with this as casting from [[string : anyobject?]] to nsmutablearray always fails Commented Sep 7, 2016 at 6:29
  • NSMutableDictionary can't contain optionals, and neither can NSMutableArray. You have to drop the optional on AnyObject. Commented Sep 7, 2016 at 6:36
  • @Avi yay! thanks Worked! Commented Sep 7, 2016 at 6:51

2 Answers 2

5

Replica of your issue:

    var ary : [[String:AnyObject]] = []
    var mutableDictionary = [String: AnyObject]()
    var mutableArray:NSMutableArray!

    for _ in 0...4 {
        mutableDictionary.updateValue("adsf", forKey: "name")
        mutableDictionary.updateValue("dsf", forKey: "phoneNumber")
        mutableDictionary.updateValue("sdfd", forKey: "id")
        ary.append(mutableDictionary)
    }

    mutableArray =  NSMutableArray(array: ary)

Removing the optional did the trick!

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks alot! worked but what problem does it cause with optional? anyidea
The only explanation I have is that: "NSMutableArray doesn't hold optionals". I hope someone with better and deep explanation will come and explain us here.
1

// try like this

Manager.sharedInstance().List(NSMutableArray(array: ary as! NSArray))

3 Comments

No it crashes with this as casting from [[string : anyobject?]] to nsmutablearray always fails
do one thing instead of this statement (var ary : [[String:AnyObject?]] = []) you can take like this var ary: [AnyObject] = []
and try above solution

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.