1

I need convert String to Unicode,like this: let str = "哈哈123abc" Because I send data is limited, so I need the most saving way,what should i do

4
  • 2
    What String representation are you starting with? What is the String representation that you want to convert to? Take a look at the Strings and Characters documentation and see if it helps to improve your question. Commented Oct 19, 2016 at 11:25
  • I am used to BLE peripheral. The name, will be limited to 18 byte, including Chinese characters, Numbers and characters, Chinese characters 3 byte, because unicode is a 2 byte, so need to string converted to unicode Commented Oct 19, 2016 at 11:31
  • 1
    What encoding does the Chinese characters have? Do you want to end up with UTF-8? Commented Oct 19, 2016 at 11:42
  • I need to convert any character to 2 byte Commented Oct 19, 2016 at 11:51

1 Answer 1

19

This way you can convert String to Unicode in swift3

var str : String = "哈哈123abc"

//String to Unicode
var dataenc = str.data(using: String.Encoding.nonLossyASCII)
var encodevalue = String(data: dataenc!, encoding: String.Encoding.utf8)

//Unicode to String
var datadec  = encodevalue?.data(using: String.Encoding.utf8)
var decodevalue = String(data: datadec!, encoding: String.Encoding.nonLossyASCII)
Sign up to request clarification or add additional context in comments.

3 Comments

oh,thanks,but,how convert Unicode to String in swift3?
How do we do this for attributed string?
encode value gives two slash and it's not working, please check your answer again

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.