无法将NSMutableDictionnary转换为[String:AnyObject]

时间:2015-11-26 12:29:21

标签: swift2

我正在向Swift 2.1转移一些管理持久性CoreData的代码。虽然我收到一个奇怪的错误,告诉我我无法将NSMutableDictionnary投射到[String: AnyObject]这是我不理解的事情

do {
    try coordinator!.addPersistentStoreWithType(NSSQLiteStoreType,
        configuration: nil, URL: url, options: options)
} catch var providedError as NSError {
    coordinator = nil
    // Report any error we got.
    let dict = NSMutableDictionary()
    dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
    dict[NSLocalizedFailureReasonErrorKey] = failureReason
    dict[NSUnderlyingErrorKey] = providedError

    let error = NSError(domain: "SOME_ERROR_DOMAIN", code: 9999,
        userInfo: dict as! [String : AnyObject]) // <--- HERE IS THE WARNING
} catch {
    fatalError()
}

警告信息:

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

我将通过直接使用Swift Dictionnary解决这个问题,但我想了解这个问题的原因。

1 个答案:

答案 0 :(得分:0)

只需使用Apple在Core Data模板中建议的代码。

let dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = providedError

let error = NSError(domain: "SOME_ERROR_DOMAIN", code: 9999, userInfo: dict)

类型为[String: AnyObject],因为类型不是可选的,所以不需要强制转换。

原因是可变集合类型NSMutableArrayNSMutableDictionary不会自动桥接到Swift对应项。