How to create a CFDictionary in an OS X target?

5.1k views Asked by At

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?

2

There are 2 answers

0
JAL On

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
0
Kildyt On

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.