如何将string转换为unicode(UTF-8)string在Swift中?

如何将string转换为unicode(UTF-8)string在Swift中?

在目标中,我可以这样写:

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

在Swift中如何做类似?

使用这个代码,

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

希望它有帮助

迅速

 let esc_str = str.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) 

Swift 4我创build了一个string扩展

 func utf8DecodedString()-> String { let data = self.data(using: .utf8) if let message = String(data: data!, encoding: .nonLossyASCII){ return message } return "" } fun utf8EncodedString()-> String { let messageData = self.data(using: .nonLossyASCII) let text = String(data: messageData!, encoding: .utf8) return text }