The following code is almost exact replica from Apple Documentation and compiles without errors:
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()
}
The line marked with !!!
contains forced downcast, while replacing as!
with as
quite obviously results in a compilation error 'Any?' is not convertible to 'SecIdentity?'...
Indeed SecIdentity
is a class while Any
may not even be a class.
What I really cannot explain is the following. If I try to make the code safer, by using this
guard let idenity = firstItem[kSecImportItemIdentity as String] as? SecIdentity
else {
throw AnError()
}
or this
guard let idenityRef = firstItem[kSecImportItemIdentity as String] as? SecIdentity?
else {
throw AnError()
}
I get a compilation error: Conditional downcast to CoreFoundation type 'SecIdentity' will always succeed
Conditional downcast...
compilation error for bothguard
s?--even for the first one withas? SecIdentity
. The error makes sense for the last guard: every value will indeed succeed because even iffirstItem[kSecImportItemIdentity as String]
isn't aSecIdentity
, it will becomenil
when downcast toSecIdentity?
, which satisfies that last guard (because of the optional?
). This makes the guard useless, hence the compilation error. Did that make sense? – Ascensive