Swift – all that glitters is not gold (casting to CFString)

Yes, it was love at first sight, but recently Swift annoys me more and more with every day that passes. Today I spent a few hours in an attempt to run a method which converts the string to the machine url (percent instead of space etc). Knowing that String requires double casting to CFString I finished with something like this:

let baseUrl = "http://example.com"
let nsBaseUrl:NSString = baseUrl as NSString
let cfBaseUrl:CFString = nsBaseUrl as CFString

let chars = "!*'();:@&=+$,/?%#[]"
let nsChars:NSString = chars as NSString
let cfChars:CFString = nsChars as CFString

var encodedCfStringRef = CFURLCreateStringByAddingPercentEscapes(

Unfortunately, the stubborn Xcode constantly tells me that the strings I provide are NSStrings, not CFStrings.


I am not the only one who struggles with same problem:

Unfortunately, Swift still needs a little polishing. I will keep you posted on the progress of my fight with this problem.

Leave a Reply