Richard
Richard

Reputation: 43

Converting Unicode in Swift

I currently have a string as follows which I received through an API call:

\n\nIt\U2019s a great place to discover Berlin and a comfortable place to come home to.

And I want to convert it into something like this which is more readable:

It's a great place to discover Berlin and a comfortable place to come home to.

I've taken a look at this post, but that's manually writing down every conversion, and there may be more of these unicode scalar characters introduced.

What I understand is \u{2019} is unicode scalar, but the format for this is \U2019 and I'm quite confused. Are there any built in methods to do this conversion?

Upvotes: 4

Views: 3723

Answers (2)

Moshe
Moshe

Reputation: 58067

This answer suggests using the NSString method stringByFoldingWithOptions.

The Swift String class has a concept called a "view" which lets you operate on the string under different encodings. It's pretty neat, and there are some views that might help you.

If you're dealing with strings in Swift, read this excellent post by Mike Ash. He discusses the idea of what a string really is with great detail and has some helpful hints for Swift 2.

Upvotes: 3

diatrevolo
diatrevolo

Reputation: 2822

Assuming you are already splitting the string and can get the offending format separately:

func convertFormat(stringOrig: String) -> Character {
    let subString = String(stringOrig.characters.split("U").map({$0})[1])
    let scalarValue = Int(subString)
    let scalar = UnicodeScalar(scalarValue!)
    return Character(scalar)
}

This will convert the String "\U2019" to the Character represented by "\u{2019}".

Upvotes: 0

Related Questions