【发布时间】:2018-08-12 04:01:11
【问题描述】:
以下代码与Apple Documentation 几乎完全相同,并且编译时没有错误:
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
【问题讨论】:
-
您是否收到 both
guards 的Conditional downcast...编译错误?--即使是第一个带有as? SecIdentity的编译错误。这个错误对于最后一个守卫是有意义的:每个值都会成功,因为即使firstItem[kSecImportItemIdentity as String]不是SecIdentity,当向下转换为SecIdentity?时,它也会变成nil,这满足最后一个守卫(因为可选?)。这使得守卫无用,因此编译错误。这有意义吗? -
丹尼尔。第一个例子怎么样?
标签: swift downcast optional-values