问题
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...
My Code:
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!#>)
}
}
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?
回答1:
Don't use CFDictionary
in Swift. (It is possible, but not worth the effort, see below.)
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
.
Example:
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)
}
}
}
}
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)
}
}
}
}
回答2:
You can cast CFDictionaryRef
to a Swift dictionary:
if let disk = DADiskCreateFromVolumePath(kCFAllocatorDefault, session, volume as CFURL), let diskinfo = DADiskCopyDescription(disk) as? [String: AnyObject] {
}
and then cast kDADiskDescriptionVolumeNetworkKey
to a Swift string:
var volumeValue = diskinfo[kDADiskDescriptionVolumeNetworkKey as String]
来源:https://stackoverflow.com/questions/42786613/cfdictionary-get-value-for-key-in-swift3