How to convert a swift String to CFString

Just cast it:

var str = "Hello, playground" as CFString
NSString(format: "type id: %d", CFGetTypeID(str))

Note that you'll need import Foundation for cast as CFString to work.
Otherwise if you only have import CoreFoundation, you'll need to force cast as! CFString.


If you want to convert a non-literal string, you have to cast it to NSString.

let replacement = "World"
let string = "Hello, \(replacement)"

let cfstring:CFString = string as NSString

Swift knows how to convert a swift string to an NSString and an NSString to a CFString, but seems not to know how to do both steps in one.

Tags:

Swift

Cfstring