CFDictionary在Swift3中获取键的值 [英] CFDictionary get Value for Key in Swift3
问题描述
我在访问CFDictionary中的特定(或任何)键时遇到问题. 老实说,我并没有真正掌握在Swift中执行此操作的方式,而且我认为它过于复杂...
I've a problem with accessing a specific (or any) key in a CFDictionary. Honestly I don't really get the way you need to do this in Swift and I think it's overly complicated...
我的代码:
if let session = DASessionCreate(kCFAllocatorDefault) {
let mountedVolumes = FileManager.default.mountedVolumeURLs(includingResourceValuesForKeys: [], options: [])!
for volume in mountedVolumes {
if let disk = DADiskCreateFromVolumePath(kCFAllocatorDefault, session, volume as CFURL) {
let diskinfo = DADiskCopyDescription(disk);
var volumeValue = CFDictionaryGetValue(diskinfo, <#T##key: UnsafeRawPointer!##UnsafeRawPointer!#>)
}
}
我要实现的目标:将键或字段 DAVolumeNetwork 的值放入变量 volumeValue 中. 我想我需要将 kDADiskDescriptionVolumeNetworkKey 传递给 CFDictionaryGetValue 方法吗?我该如何实现?
What I want to achieve: Get the Value for the Key or field DAVolumeNetwork into the variable volumeValue. I guess I need to pass the kDADiskDescriptionVolumeNetworkKey to the CFDictionaryGetValue Method? How do I achieve this?
推荐答案
在Swift中不要使用CFDictionary
. (有可能,但不值得付出努力,请参阅下文.)
Don't use CFDictionary
in Swift. (It is possible, but not worth the effort, see below.)
-
CFDictionary
是免费电话 与NSDictionary
桥接,又可以转换为SwiftDictionary
. -
kDADiskDescriptionVolumeNetworkKey
键的值是一个CFBoolean
可以转换为SwiftBool
.
CFDictionary
is toll-free bridged withNSDictionary
, which in turn can be cast to a SwiftDictionary
.- The value of the
kDADiskDescriptionVolumeNetworkKey
key is aCFBoolean
which can be cast to a SwiftBool
.
示例:
if let session = DASessionCreate(kCFAllocatorDefault),
let mountedVolumes = FileManager.default.mountedVolumeURLs(includingResourceValuesForKeys: []) {
for volume in mountedVolumes {
if let disk = DADiskCreateFromVolumePath(kCFAllocatorDefault, session, volume as CFURL),
let diskinfo = DADiskCopyDescription(disk) as? [NSString: Any] {
if let networkValue = diskinfo[kDADiskDescriptionVolumeNetworkKey] as? Bool {
print(networkValue)
}
}
}
}
仅出于完整性考虑:这是必要的指针
忙于在Swift 3中调用CFDictionaryGetValue
Just for the sake of completeness: This is the necessary pointer
juggling to call CFDictionaryGetValue
in Swift 3:
if let session = DASessionCreate(kCFAllocatorDefault),
let mountedVolumes = FileManager.default.mountedVolumeURLs(includingResourceValuesForKeys: []) {
for volume in mountedVolumes {
if let disk = DADiskCreateFromVolumePath(kCFAllocatorDefault, session, volume as CFURL),
let diskinfo = DADiskCopyDescription(disk) {
if let ptr = CFDictionaryGetValue(diskinfo, Unmanaged.passUnretained(kDADiskDescriptionVolumeNetworkKey).toOpaque()) {
let networkValue = Unmanaged<NSNumber>.fromOpaque(ptr).takeUnretainedValue()
print(networkValue.boolValue)
}
}
}
}
这篇关于CFDictionary在Swift3中获取键的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!