Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access CFDictionary in Swift 3?

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

func CFDictionaryGetValue(CFDictionary!, UnsafeRawPointer!)

How the heck do I convert my key (a string) to an UnsafeRawPointer so I can pass it to this call?

like image 687
Trevor Alyn Avatar asked Sep 16 '16 22:09

Trevor Alyn


3 Answers

If you don't have to deal with other Core Foundation functions expecting an CFDictionary, you can simplify it by converting to Swift native Dictionary:

if let dict = cfDict as? [String: AnyObject] {
    print(dict["key"])
}
like image 80
Code Different Avatar answered Oct 16 '22 05:10

Code Different


Be careful converting a CFDictionary to a Swift native dictionary. The bridging is actually quite expensive as I just found out in my own code (yay for profiling!), so if it's being called quite a lot (as it was for me) this can become a big issue.

Remember that CFDictionary is toll-free bridged with NSDictionary. So, the fastest thing you can do looks more like this:

let cfDictionary: CFDictionary = <code that returns CFDictionary>
if let someValue = (cfDictionary as NSDictionary)["some key"] as? TargetType {
    // do stuff with someValue
}
like image 45
Gabriel Avatar answered Oct 16 '22 06:10

Gabriel


What about something like:

var key = "myKey"
let value = withUnsafePointer(to: &key){ upKey in
    return CFDictionaryGetValue(myCFDictionary, upKey)
}
like image 2
Jans Avatar answered Oct 16 '22 06:10

Jans