简体   繁体   中英

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?

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)
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM