How can I cast `Any?` to CF types?

let x: Any? = nil

x as? CFDictionary
// error: Conditional downcast to CoreFoundation type 'CFDictionary' will always succeed

x as CFDictionary
// error: 'Any?' is not convertible to 'CFDictionary'; did you mean to use 'as!' to force downcast?

x as CFDictionary?
// error: 'Any?' is not convertible to 'CFDictionary?'; did you mean to use 'as!' to force downcast?

x as? CFDictionary?
// error: Conditional downcast to CoreFoundation type 'CFDictionary' will always succeed

The error message is really confusing...

This works… but it's super ugly. This is not an ideal solution.

x as? NSDictionary as CFDictionary?

The Swift runtime doesn't currently support querying the types of opaque CF type pointers through using CFGetTypeID (so it just allows the cast to always succeed regardless) – you can however implement the logic yourself, see for example:

1 Like
Terms of Service

Privacy Policy

Cookie Policy