Why is unicode included as an Encoding in Swift's String API?

大兔子大兔子 提交于 2020-01-03 03:17:06

问题


I read this very important blog regarding string encodings.

After reading it I realized that unicode is a standard of mapping characters to code points which are integers. How these integers are stored in memory is an entirely different concept. This is where .utf8, .utf16 come into play, defining the way we store these integers in memory.

In the Swift String API there is a method which gives us the data bytes used to represent the String in various encodings:

func data(using encoding: String.Encoding, allowLossyConversion: Bool = false) -> Data?

The first parameter to this method is of Type String.Encoding. This struct Encoding has an encoding declared as:

static let unicode: String.Encoding

Now suddenly the method can give me data representation of the String using the encoding .unicode

Now this is in fact opposite to what I concluded after reading the mentioned blog. Its giving me data representation of a string, even thought unicode does not provide me details of how it can be stored.

Can any one tell me what am I missing here? I am really confused now.


回答1:


String.Encoding.unicode is the same as String.Encoding.utf16

print(String.Encoding.unicode)
print(String.Encoding.utf16)

The above prints:

  • Unicode (UTF-16)
  • Unicode (UTF-16)


来源:https://stackoverflow.com/questions/57288344/why-is-unicode-included-as-an-encoding-in-swifts-string-api

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