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

北城余情 提交于 2019-12-17 19:48:43

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!