问题
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?
回答1:
Use this code,
let str = String(UTF8String: strToDecode.cStringUsingEncoding(NSUTF8StringEncoding))
hope its helpful
回答2:
Swift 4 I have created a String extension
func utf8DecodedString()-> String {
let data = self.data(using: .utf8)
if let message = String(data: data!, encoding: .nonLossyASCII){
return message
}
return ""
}
func utf8EncodedString()-> String {
let messageData = self.data(using: .nonLossyASCII)
let text = String(data: messageData!, encoding: .utf8)
return text
}
回答3:
Swift 4:
let str = String(describing: strToDecode.cString(using: String.Encoding.utf8))
来源:https://stackoverflow.com/questions/37087325/how-to-convert-string-to-unicodeutf-8-string-in-swift