Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert unicode symbols \uXXXX in String to Character in Swift

I'm receiving via a REST API a string which contains unicode encoded characters in form of \uXXXX

e.g. Ain\u2019t which should be Ain’t

Is there a nice way to convert these?

like image 781
Jan Avatar asked Jan 05 '16 00:01

Jan


2 Answers

You can use \u{my_unicode}:

print("Ain\u{2019}t this a beautiful day")
/* Prints "Ain’t this a beautiful day"

From the Language Guide - Strings and Characters - Unicode:

String literals can include the following special characters:

...

  • An arbitrary Unicode scalar, written as \u{n}, where n is a 1–8 digit hexadecimal number with a value equal to a valid Unicode code point
like image 140
dfrib Avatar answered Oct 18 '22 05:10

dfrib


You can apply a string transform StringTransform:

extension String {
    var decodingUnicodeCharacters: String { applyingTransform(.init("Hex-Any"), reverse: false) ?? "" }
}

let string = #"Ain\u2019t"#
print(string.decodingUnicodeCharacters)  // "Ain’t\n"
like image 6
Leo Dabus Avatar answered Oct 18 '22 06:10

Leo Dabus