Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Swift to unescape unicode characters, ie \u1234

Tags:

swift

utf-8

I have problems with special characters when using JSON in xcode 6 with swift

I found these codes in Cocoa/objective C to solve some problems converting accent but could not make it work in Swift. Any suggestions for how to use it? ... best alternative suggestions would also be cool ...

Thanks

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!
like image 275
user3758109 Avatar asked Nov 30 '22 11:11

user3758109


1 Answers

It's fairly similar in Swift, though you still need to use the Foundation string classes:

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: 各個都

(The last parameter threw me for a loop until I realized that Boolean in Swift is a type alias for UInt - YES in Objective-C becomes 1 in Swift for these types of methods.)

like image 167
Nate Cook Avatar answered Dec 02 '22 01:12

Nate Cook