在使用swift
的xcode 6中使用JSON时,我遇到了特殊字符的问题我在Cocoa / Objective C中找到了这些代码来解决转换重音的一些问题但却无法在Swift中运行。有关如何使用它的任何建议? ......最好的替代建议也很酷......
由于
NSString *input = @"\\u5404\\u500b\\u90fd";
NSString *convertedString = [input mutableCopy];
CFStringRef transform = CFSTR("Any-Hex/Java");
CFStringTransform((__bridge CFMutableStringRef)convertedString, NULL, transform, YES);
NSLog(@"convertedString: %@", convertedString);
// prints: 各個都, tada!
答案 0 :(得分:12)
它在Swift中非常相似,但你仍然需要使用Foundation字符串类:
let transform = "Any-Hex/Java"
let input = "\\u5404\\u500b\\u90fd" as NSString
var convertedString = input.mutableCopy() as NSMutableString
CFStringTransform(convertedString, nil, transform as NSString, 1)
println("convertedString: \(convertedString)")
// convertedString: 各個都
(最后一个参数引发了我的循环,直到我意识到Swift中的Boolean
是UInt的类型别名 - 对于这些类型的方法,Objective-C中的YES在Swift中变为1。)
答案 1 :(得分:3)
Swift 3
let transform = "Any-Hex/Java"
let input = "\\u5404\\u500b\\u90fd" as NSString
var convertedString = input.mutableCopy() as! NSMutableString
CFStringTransform(convertedString, nil, transform as NSString, true)
print("convertedString: \(convertedString)")
// convertedString: 各個都
答案 2 :(得分:0)
Swift 4字符串扩展名
extension String {
var unescapingUnicodeCharacters: String {
let mutableString = NSMutableString(string: self)
CFStringTransform(mutableString, nil, "Any-Hex/Java" as NSString, true)
return mutableString as String
}
}