How to access CFDictionary in Swift 3?

I need to read and write some data from instances of CFDictionary (to read and update EXIF โ€‹โ€‹data in photos). For life, I canโ€™t figure out how to do this in Swift 3. The signature for the call I want is:

 func CFDictionaryGetValue(CFDictionary!, UnsafeRawPointer!) 

How can I convert my key (string) to UnsafeRawPointer to pass it to this call?

+11
source share
4 answers

If you donโ€™t need to deal with other Core Foundation features awaiting CFDictionary , you can simplify this conversion to Swift native Dictionary :

 if let dict = cfDict as? [String: AnyObject] { print(dict["key"]) } 
+12
source

Be careful when converting CFDictionary to your own Swift dictionary. Bridging is actually quite expensive, as I just found out in my own code (cheers for profiling!), So if it is called quite often (as it was for me), this can be a big problem.

Remember that CFDictionary is free on NSDictionary with NSDictionary . So the fastest thing you can do is something like this:

 let cfDictionary: CFDictionary = <code that returns CFDictionary> if let someValue = (cfDictionary as NSDictionary)["some key"] as? TargetType { // do stuff with someValue } 
+3
source

Sort of:

 var key = "myKey" let value = withUnsafePointer(to: &key){ upKey in return CFDictionaryGetValue(myCFDictionary, upKey) } 
+1
source

You can write something like the following:

 let key = "some key" as NSString if let rawResult = CFDictionaryGetValue(cfDictionary, Unmanaged.passUnretained(key).toOpaque()) { let result = Unmanaged<AnyObject>.fromOpaque(rawResult).takeUnretainedValue() print(result) } 

But I think you would not want to write such a thing any time when you are extracting some data from this CFDictionary . You better convert it to a Swift Dictionary , as suggested in the Code Different answer.

-one
source

All Articles