Eman H Eman H - 1 year ago 103
Swift Question

I receive an improperly formatted unicode in a String

I am working with a web API that gives me strings like the following:

"Eat pok\u00e9."

Xcode complains that

Expected Hexadecimal code in braces after unicode escape

My understanding is that it should be converted to
, but I do not know how to achieve this.

Can anybody point me in the right direction for me develop a way of converting these as there are many in this API?

I also need to remove
from the strings.

Rob Rob
Answer Source

You may want to give us more context regarding what the raw server payload looked like, and show us how you're displaying the string. Some ways of examining strings in the debugger (or if you're looking at raw JSON) will show you escape strings, but if you use the string in the app, you'll see the actual Unicode character.

I wonder if you're just looking at raw JSON. For example, I passed the JSON, {"foo": "Eat pok\u00e9."} to the following code:

let jsonString = String(data: data, encoding: NSUTF8StringEncoding)!
let dictionary = try! NSJSONSerialization.JSONObjectWithData(data, options: []) as! [String: String]

And it output:

{"foo": "Eat pok\u00e9."}
Eat poké.

By the way, this standard JSON escape syntax should not be confused with Swift's string literal escape syntax, in which the hex sequence must be wrapped in braces:

print("Eat pok\u{00e9}.")

Swift uses a different escape syntax in their string literals, and it should not be confused with that employed by formats like JSON.