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

cast from [String:AnyObject] to unrelated type NSMutableDictionary always fails Warning

代码可以正常工作,但我如何消除这个每次都出现的警告?

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

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

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
}

尝试更换

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

有了这个:

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

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

初始化一个新的

编辑:请参阅@Tommy 对这个问题的评论,了解为什么这是必要的。

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"]!
}

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