Cast from [String: AnyObject] for an unrelated type NSMutableDictionary always fails Warning

The code works, but how can I turn off this warning, which keeps popping up every time?

let parentView = self.parentViewController as! SBProfileViewController parentView.savedDetailsModel = SBSavedUserModel(data:responseObject["data"].dictionaryObject! as! NSMutableDictionary) 

cast from '[String: AnyObject]' for an unrelated type 'NSMutableDictionary' always fails Warning

SavedUserModel saves the saved information: -

 class SBSavedUserModel : NSObject { var userId : String! var firstName : String! var lastName : String! var imageBase64 : String! required init ( data : NSMutableDictionary) { self.userId = data.objectForKey("userId") as! String self.firstName = data.objectForKey("fName") as! String self.lastName = data.objectForKey("lName") as! String self.imageBase64 = data.objectForKey("image") as! String } 
+6
source share
3 answers

Try replacing

responseObject["data"].dictionaryObject! as! NSMutableDictionary

with this:

NSMutableDictionary(dictionary: responseObject["data"].dictionaryObject!)

You can easily include it in an NSDictionary, but for some reason, when you need an NSMutableDictionary, you have to initialize a new one with NSMutableDictionary(dictionary:)

Edit: See the comment on this from @Tommy why this is necessary.

+4
source

Unlike NSArray and NSDictionary mutable Foundation collection types NSMutableArray and NSMutableDictionary not bound to Swift counterparts.

The easiest solution is to continue using native Swift types.

 let parentView = self.parentViewController as! SBProfileViewController parentView.savedDetailsModel = SBSavedUserModel(data:responseObject["data"].dictionaryObject!) ... class SBSavedUserModel : NSObject { var userId, firstName, lastName, imageBase64 : String required init ( data : [String:AnyObject]) { self.userId = data["userId"] as! String self.firstName = data["fName"] as! String self.lastName = data["lName"] as! String self.imageBase64 = data["image"] as! String } } 

Or - even more convenient if the values ​​in the dictionary are all strings

 parentView.savedDetailsModel = SBSavedUserModel(data:responseObject["data"].dictionaryObject as! [String:String]) ... required init ( data : [String:String]) { self.userId = data["userId"]! self.firstName = data["fName"]! self.lastName = data["lName"]! self.imageBase64 = data["image"]! } 
+2
source

Hope this way helps you: mutableDictionary as NSDictionary as? [String: AnyObject] mutableDictionary as NSDictionary as? [String: AnyObject] The same thing works with NSMutableArray.

-1
source

All Articles