Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 961
Dirder Avatar asked May 07 '16 10:05

Dirder


People also ask

What is UTF-8 in Swift?

UTF8View Elements Match Encoded C Strings Swift streamlines interoperation with C string APIs by letting you pass a String instance to a function as an Int8 or UInt8 pointer. When you call a C function using a String , Swift automatically creates a buffer of UTF-8 code units and passes a pointer to that buffer.

What is UTF-8 and UTF 16 in Swift?

Both UTF-8 and UTF-16 are variable-width encodings, but UTF-16 is variable width up to 2 while UTF-8 is variable width up to 4. This makes UTF-16 simpler for decoding and on-the-fly validation for non-ASCII content.

What is string encoding in Swift?

Overview. A string is a series of characters, such as "Swift" , that forms a collection. Strings in Swift are Unicode correct and locale insensitive, and are designed to be efficient. The String type bridges with the Objective-C class NSString and offers interoperability with C functions that works with strings.

What is a UTF-8 string?

UTF-8 is a Unicode character encoding method. This means that UTF-8 takes the code point for a given Unicode character and translates it into a string of binary. It also does the reverse, reading in binary digits and converting them back to characters.


2 Answers

Swift 4:

let str = String(describing: strToDecode.cString(using: String.Encoding.utf8))
like image 76
Alessandro Ornano Avatar answered Oct 18 '22 05:10

Alessandro Ornano


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
    }
}
like image 15
Gurjinder Singh Avatar answered Oct 18 '22 05:10

Gurjinder Singh