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?
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.
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.
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.
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.
let str = String(describing: strToDecode.cString(using: String.Encoding.utf8))
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With