'NSMutableDictionary'不能转换为'[NSObject:AnyObject]'swift 2.0

时间:2015-09-29 07:42:31

标签: swift2

更新到swift 2.0后 之前出现了一些错误, 这是代码

let dict = NSMutableDictionary()   
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason   
dict[NSUnderlyingErrorKey] = error      
error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict as [NSObject: AnyObject])

错误信息如下:

'NSMutableDictionary' is not convertible to '[NSObject : AnyObject]'

有关如何修复的想法吗?

2 个答案:

答案 0 :(得分:2)

我无法重现您的问题,但有一些建议完全避免NSMutableDictionary(从而消除了演员阵容):

  1. 您可以直接使用Swift Dictionary,无需演员:

    var dict = [NSObject: AnyObject]()
    dict[NSLocalizedDescriptionKey]        = "Failed to initialize the application's saved data"
    dict[NSLocalizedFailureReasonErrorKey] = failureReason
    dict[NSUnderlyingErrorKey]             = error
    
  2. 您也可以在单个语句中声明字典和键/值:

    let dict: [NSObject : AnyObject] = [
        NSLocalizedDescriptionKey        : "Failed to initialize the application's saved data",
        NSLocalizedFailureReasonErrorKey : failureReason,
        NSUnderlyingErrorKey             : error
    ]
    

答案 1 :(得分:0)

我已经浏览了您的代码,我修改如下。请看下面的代码:

var dict = NSMutableDictionary() as [NSObject : AnyObject]
let error :NSError = {    return NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict as [NSObject: AnyObject]) }()

dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = "hello"
dict[NSUnderlyingErrorKey] = error