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

By | July 29, 2014

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(
  kCFAllocatorDefault,
  cfBaseUrl,
  nil,
  cfChars,
  CFStringEncoding(UTF8)
)

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

swift-nsstring-to-cfstring

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