0

由于 Swift 中的 UnsafePointer,我感到头疼。

这是我要调用的方法:

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

我就是这样做的。

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


let list = SCDynamicStoreCopyProxies(ds)

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

然而,这会返回一个错误。我不知道如何将字典键传递给这个方法。如果我删除UnsafePointer("HTTPPort")"HTTPPort"改用,我会收到运行时错误。”

如何访问字典值?

4

1 回答 1

1

CFDictionary最简单的解决方案是利用和之间的免费桥接NSDictionary,并使用NSDictionary 访问器方法:

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

但只是为了完整起见:可以通过以下方式完成 CFDictionaryGetValue

if let list = SCDynamicStoreCopyProxies(ds)  {
    let key = kSCPropNetProxiesHTTPPort
    let port = unsafeBitCast(CFDictionaryGetValue(list, unsafeAddressOf(key)), NSObject!.self)
    if port != nil {
        print("HTTPPort:", port)
    }
}
于 2016-03-23T09:58:02.770 回答