0

There is this function in Alamofire

func escape(string: String) -> String {
    let legalURLCharactersToBeEscaped: CFStringRef = ":/?&=;+!@#$()',*"

    return CFURLCreateStringByAddingPercentEscapes(nil, string, nil, legalURLCharactersToBeEscaped, CFStringBuiltInEncodings.UTF8.rawValue)

}

Complier show "CFString! is not convertible to String" error in this func. I have tried Convert CFString to NSString - Swift to cast this , but have no luck.

Community
  • 1
  • 1
Niks
  • 87
  • 2
  • 8

1 Answers1

5

From the Xcode 6.3 Release Notes:

The implicit conversions from bridged Objective-C classes (NSString/NSArray/NSDictionary) to their corresponding Swift value types (String/Array/Dictionary) have been removed, making the Swift type system simpler and more predictable.
...
In order to perform such a bridging conversion, make the conversion explicit with the as keyword.

You have to convert CFString/NSString to a Swift String explicitly:

func escape(string: String) -> String {
    let legalURLCharactersToBeEscaped: CFStringRef = ":/?&=;+!@#$()',*"

    return CFURLCreateStringByAddingPercentEscapes(nil, string,
        nil, legalURLCharactersToBeEscaped,
        CFStringBuiltInEncodings.UTF8.rawValue) as String
                                     // HERE ---^
}

The conversion in the other direction (Swift String to NSString) is still done automatically, that's why the the string parameter of your function can be passed directly to the CFURLCreateStringByAddingPercentEscapes() function which expects a CFString argument.

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382