CFError到NSError的免费桥接在Swift 3

时间:2016-11-14 18:44:56

标签: swift swift3 core-foundation

将我们的代码库转换为Swift 3,我遇到了这个问题:

ABAddressBookRequestAccessWithCompletion(addressBookRef) { (granted: Bool, error: CFError?) in
        DispatchQueue.main.async {

            if let nsError = error as NSError {
                ...   
            }
        }
}

编译器错误是: Cannot convert value of type 'CFError?' to type 'NSError' in coercion

更改为:

if let nsError = error as? NSError { ... }

发出警告:Cast from 'CFError?' to unrelated type 'NSError' always fails

1 个答案:

答案 0 :(得分:6)

根本不要尝试通过NSError。直接强制错误,Swift类型。

if let err = error as? Error {
    print(err) // no problem
}