如何在OS X目标中创建CFDictionary?

时间:2015-03-27 12:59:54

标签: swift macos core-foundation cfstring cfdictionary

根据documentation CFDictionaryCreate用于在swift中实例化CFDictionary。

func CFDictionaryCreate(_ allocator: CFAllocator!,
                  _ keys: UnsafeMutablePointer<UnsafePointer<Void>>,
                  _ values: UnsafeMutablePointer<UnsafePointer<Void>>,
                  _ numValues: CFIndex,
                  _ keyCallBacks: UnsafePointer<CFDictionaryKeyCallBacks>,
                  _ valueCallBacks: UnsafePointer<CFDictionaryValueCallBacks>) -> CFDictionary!

如何创建keysvalues参数? 到目前为止,我已尝试使用swift的String类型,希望它会自动转换为适当的类型:

import Foundation

var keys : [String] = ["key1", "key2"]
var values : [String] = ["value1", "value2"]
var keyCallbacks = kCFTypeDictionaryKeyCallBacks
var valueCallbacks = kCFTypeDictionaryValueCallBacks
var dict : CFDictionary = CFDictionaryCreate(kCFAllocatorDefault,
    &keys, &values, 2, &keyCallbacks, &valueCallbacks)

很遗憾,我收到一条错误消息,指出String不是keysvalues数组元素的正确类型:

main.swift:41:2: error: 'String' is not identical to 'UnsafePointer<Void>'
    &configKeys, &configValues, 3, &keyCallbacks, &valueCallbacks)

如何从UnsafePointer<Void>制作String

2 个答案:

答案 0 :(得分:6)

对于Swift 3,您需要额外投射到CFDictionary。 否则上下文类型&#39; CFDictionary&#39;不能与字典一起使用文字被抛出。

let options: CFDictionary = [kSecImportExportPassphrase as String : "certificateKey"] as CFDictionary

有关详情,请参阅https://bugs.swift.org/browse/SR-2388

答案 1 :(得分:2)

rintaro的评论适用于字符串文字,但不适用于我使用CFStringRef和Swift String的时候:

// Error: Contextual type 'CFDictionary' cannot be used with dictionary literal
let options: CFDictionary = [kSecImportExportPassphrase : "certificateKey"]

我必须将CFStringRef转换为Swift String:

let options: CFDictionary = [kSecImportExportPassphrase as String : "certificateKey"] // works