How to create a CFDictionary in an OS X target?

▼魔方 西西 提交于 2019-12-10 09:26:29

问题


According to documentation CFDictionaryCreate is used to instantiate CFDictionary in swift.

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

How can I create the keys and values arguments? So far I've tried to use swift's String type hoping it would be automatically converted to appropriate types:

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)

Unfortunately I receive an error saying String is not the right type for keys and values array elements:

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

How do I make an UnsafePointer<Void> from String?


回答1:


For Swift 3 you need extra casting to CFDictionary. Otherwise Contextual type 'CFDictionary' cannot be used with dictionary literal is thrown.

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

See https://bugs.swift.org/browse/SR-2388 for more.




回答2:


rintaro's comment worked for String literals, but not when I was working with a CFStringRef and a Swift String:

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

I had to cast the CFStringRef as a Swift String:

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


来源:https://stackoverflow.com/questions/29301302/how-to-create-a-cfdictionary-in-an-os-x-target

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!