从[String:AnyObject]转换为不相关的类型NSMutableDictionary总是失败警告

时间:2016-02-06 19:11:02

标签: ios swift dictionary casting nsmutabledictionary

代码正在运行,但我如何沉默这种每次都出现的警告?

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

从'[String:AnyObject]'转换为不相关的类型'NSMutableDictionary'总是失败警告

SavedUserModel存储已保存的信息: -

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
}

3 个答案:

答案 0 :(得分:4)

尝试替换

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

用这个:

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

您可以轻松地将其转换为NSDictionary,但出于某种原因,当您需要NSMutableDictionary时,必须使用NSMutableDictionary(dictionary:)初始化一个新的

编辑:请参阅@Tommy对此问题的评论,了解为何需要这样做。

答案 1 :(得分:2)

NSArrayNSDictionary不同,可变Foundation集合类型NSMutableArrayNSMutableDictionary未与Swift对等方框架桥接。

最简单的解决方案是继续使用Swift原生类型

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

或者 - 如果字典中的所有值都是字符串

,则更方便
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 :(得分:-1)

希望这种方式可以帮助你: mutableDictionary as NSDictionary as? [String: AnyObject] 同样适用于NSMutableArray。