iphone - CF字符串!在 swift 1.2 中不能转换为 String

标签 iphone swift

Alamofire中有这个功能

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

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

}

编译器在此函数中显示“CFString!不可转换为字符串”错误。我试过Convert CFString to NSString - Swift投这个,但没有运气。

最佳答案

来自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.

您必须显式地将 CFString/NSString 转换为 Swift String:

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

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

另一个方向的转换(Swift StringNSString)仍然是自动完成的,这就是为什么你的 string 参数 函数可以直接传递给 CFURLCreateStringByAddingPercentEscapes() 函数 一个 CFString 参数。

关于iphone - CF字符串!在 swift 1.2 中不能转换为 String,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29556312/

相关文章:

ios - 不同的 iPhone 模拟器尺寸会导致节点错位

ios - 从 PFFile 到 PFFile 的条件转换总是成功

ios - 在 Swift 中,如何更改字符串的一部分的属性?

swift - 通过文本域调用变量名

swift - SKAction.move(to : . ..) 和 SKAction.move(by : . ..) 对我来说完全一样

ios - 如何在 ios 的数字键盘键盘中为所有文本字段添加下一个按钮并导航到下一个

iphone - 是否可以将外部摄像头模块连接到 iPhone 音频插孔?

iphone - 频繁asihttprequest runrequests crash

iphone - 匹配 NSString 中单词的开头

ios - removeFromSuperview() 并不总是有效