根据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!
如何创建keys
和values
参数?
到目前为止,我已尝试使用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
不是keys
和values
数组元素的正确类型:
main.swift:41:2: error: 'String' is not identical to 'UnsafePointer<Void>'
&configKeys, &configValues, 3, &keyCallbacks, &valueCallbacks)
如何从UnsafePointer<Void>
制作String
?
答案 0 :(得分:6)
对于Swift 3,您需要额外投射到CFDictionary
。
否则上下文类型&#39; CFDictionary&#39;不能与字典一起使用文字被抛出。
let options: CFDictionary = [kSecImportExportPassphrase as String : "certificateKey"] as CFDictionary
答案 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