6

以下代码几乎与Apple 文档完全相同,编译时没有错误:

guard let firstItem = (rawItems! as? Array<Dictionary<String, Any>>)?.first else {
    throw AnError()
}

let identityRef = firstItem[kSecImportItemIdentity as String] 
               as! SecIdentity?   // !!!

guard let identity = identityRef else {
    throw AnError()
}

标记为的行!!!包含强制向下转换,而替换as!as很明显会导致编译错误'Any?' is not convertible to 'SecIdentity?'...确实SecIdentity是一个类,而Any可能甚至不是一个类。

我真正无法解释的是以下内容。如果我尝试使代码更安全,请使用此

guard let idenity = firstItem[kSecImportItemIdentity as String] as? SecIdentity
else {
    throw AnError()
}

或这个

guard let idenityRef = firstItem[kSecImportItemIdentity as String] as? SecIdentity?
else {
    throw AnError()
}

我得到一个编译错误:Conditional downcast to CoreFoundation type 'SecIdentity' will always succeed

4

2 回答 2

7
于 2018-08-12T07:26:48.823 回答
2

CoreFoundation 类型的行为与 Foundation 类型略有不同。

不要有条件地贬低身份。如果可选绑定成功,您可以强制解包身份

guard let idenity = firstItem[kSecImportItemIdentity as String] else { throw AnError() }
var privateKey : SecKey?
let status = SecIdentityCopyPrivateKey(identity as! SecIdentity, &privateKey)

边注 :

请永远不要写as? SecIdentity?
要么是有条件的向下转换as? SecIdentity,要么是桥式转换为可选的as SecIdentity?

于 2018-08-12T06:08:35.900 回答