20

How to convert string to unicode(UTF-8) string in Swift?

In Objective I could write smth like that:

NSString *str = [[NSString alloc] initWithUTF8String:[strToDecode cStringUsingEncoding:NSUTF8StringEncoding]];

how to do smth similar in Swift?

2
  • Maybe you can change how you decode it when you receive it? Like stackoverflow.com/questions/31733254/… , is this similar? Commented May 7, 2016 at 11:55
  • Thanks, but it does not fit for me. simply speaking I need to convert this : let string = "ÐаÑпаÑи пÑогÑали ÑÑÑбоÐ" to this let result = "Карпати програли футбол" . I did it with online converters converting to Unicode(UTF-8) Commented May 7, 2016 at 12:15

3 Answers 3

16

Swift 4 and 5 I have created a String extension

extension String {
    func utf8DecodedString()-> String {
        let data = self.data(using: .utf8)
        let message = String(data: data!, encoding: .nonLossyASCII) ?? ""
        return message
    }
    
    func utf8EncodedString()-> String {
        let messageData = self.data(using: .nonLossyASCII)
        let text = String(data: messageData!, encoding: .utf8) ?? ""
        return text
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

youre missing a 'c' in your second function (you wrote fun utf8EncodedString())
@JoshO'Connor Thanks!!
14

Swift 4:

let str = String(describing: strToDecode.cString(using: String.Encoding.utf8))

Comments

11

Use this code,

let str = String(UTF8String: strToDecode.cStringUsingEncoding(NSUTF8StringEncoding))

hope its helpful

5 Comments

thanks, but this way does solve my problem. I like before got incorrectly displayed not Latin symbols :-(
I have a string like this: " @ Rock-ЦиÑаÑа: Deep Purple " with unicode symbols (cyrilic etc). When I use online converter to Unicode(UTF-8) I can convert that to this: "@ Rock-Цитата: Deep Purple" Question is: How to do that in Swift?
simply speaking I need to convert this : let string = "ÐаÑпаÑи пÑогÑали ÑÑÑбоÐ" to this let result = "Карпати програли футбол" . I did it with online converters converting to Unicode(UTF-8)
what is the online converter please mention here and from what format to UTF-8 please mention the two formats also
let cString = qString.cString(using: String.Encoding.utf8)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.