san
san

Reputation: 3328

How to pass parameter of type UnsafeMutablePointer<UnsafePointer<Void>>

I have to use CFDictionaryCreate method in Swift(documentation link).

I am having a hard time to initialize the input parameters correctly in order to pass parameters(keys and values) of type UnsafeMutablePointer<UnsafePointer<Void>>.

Here is my code:

    var font_name: CFStringRef! = CFStringCreateWithCString(nil, "Courier", kCFStringEncodingASCII)
    var font: CTFontRef! = CTFontCreateWithName(font_name, 25.0, nil)
    var keys: [UnsafePointer<Void>] = ???? // how to intialize with "kCTFontAttributeName"
    var values: [UnsafePointer<Void>] = ???? // how to intialize with "font" variable
    var keyCallBacks = kCFTypeDictionaryKeyCallBacks
    var valueCallBacks = kCFTypeDictionaryValueCallBacks
    var font_attributes: CFDictionaryRef! = CFDictionaryCreate(kCFAllocatorDefault,   &keys, &values, sizeofValue(keys), &keyCallBacks, &valueCallBacks)
    var attr_string: CFAttributedStringRef! = CFAttributedStringCreate(nil, "hello", font_attributes)

Upvotes: 1

Views: 1559

Answers (1)

Martin R
Martin R

Reputation: 540105

You can simply use a Swift dictionary of type [ NSString : AnyObject ], which is automatically bridged to NSDictionary or CFDictionary. Note that you don't need CFStringRef either.

let font = CTFontCreateWithName("Courier", 25.0, nil)
let attributes : [ NSString : AnyObject ] = [ kCTFontAttributeName : font ]
let attrString = CFAttributedStringCreate(nil, "Hello", attributes)

Alternatively,

let attrString = NSAttributedString(string: "Hello", attributes: attributes)

because NSAttributedString is toll-free bridged with CFAttributedString.


Just for the sake of completeness, here is how you could use CFDictionaryCreate():

let font = CTFontCreateWithName("Courier", 25.0, nil)
var keys = [ unsafeAddressOf(kCTFontAttributeName) ]
var values = [ unsafeAddressOf(font) ]
var keyCallbacks = kCFTypeDictionaryKeyCallBacks
var valueCallbacks = kCFTypeDictionaryValueCallBacks
let attributes = CFDictionaryCreate(nil, &keys, &values, 1, &keyCallbacks, &valueCallbacks)
let attrString = CFAttributedStringCreate(nil, "Hello", attributes)

Upvotes: 5

Related Questions