如何传递类型UnsafeMutablePointer的参数<unsafepointer <void>&gt;

时间:2015-05-09 18:23:39

标签: ios swift

我必须在Swift中使用CFDictionaryCreate方法(documentation link)。

我很难正确初始化输入参数,以便传递UnsafeMutablePointer<UnsafePointer<Void>>类型的参数(键和值)。

这是我的代码:

    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)

1 个答案:

答案 0 :(得分:5)

您可以简单地使用类型为[ NSString : AnyObject ]的Swift词典,该词典会自动桥接到NSDictionaryCFDictionary。请注意,您也不需要CFStringRef

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

可替换地,

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

因为NSAttributedString是免费的桥接 CFAttributedString

为了完整起见,以下是您可以使用的方法 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)