Search code examples
iosswiftcocoaswift2cfdictionary

pass dictionary key to CFDictionaryGetValue


I am getting a headache due to UnsafePointer in Swift.

This is the method I want to call:

func CFDictionaryGetValue(theDict: CFDictionary!, _ key: UnsafePointer<Void>) -> UnsafePointer<Void>

And this is how I do it.

 let ds: SCDynamicStoreRef = SCDynamicStoreCreate(nil, "setNet" as CFString, nil, nil)!


let list = SCDynamicStoreCopyProxies(ds)

print(list!)
print(CFDictionaryGetValue(list, UnsafePointer("HTTPPort")))

This however returns an error. I have no idea how to pass dictionary key to this method. If I remove the UnsafePointer("HTTPPort") and use "HTTPPort" instead I get a runtime error."

How can you access the dictionary values?


Solution

  • The easiest solution is to take advantage of the toll-free bridging between CFDictionary and NSDictionary, and use the NSDictionary accessor methods:

    let ds = SCDynamicStoreCreate(nil, "setNet", nil, nil)!
    
    if let list = SCDynamicStoreCopyProxies(ds) as NSDictionary? {
        if let port = list[kSCPropNetProxiesHTTPPort as NSString] as? Int {
            print("HTTPPort:", port)
        }
    }
    

    But just for the sake of completeness: It can be done with CFDictionaryGetValue:

    if let list = SCDynamicStoreCopyProxies(ds)  {
        let key = kSCPropNetProxiesHTTPPort
        let port = unsafeBitCast(CFDictionaryGetValue(list, unsafeAddressOf(key)), NSObject!.self)
        if port != nil {
            print("HTTPPort:", port)
        }
    }