简体   繁体   English

为什么在Swift的String API中将Unicode包含为编码?

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

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. 阅读后,我意识到unicode是将字符映射到整数的代码点的标准。 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. 这就是.utf8.utf16发挥作用的地方,它定义了我们将这些整数存储在内存中的方式。

In the Swift String API there is a method which gives us the data bytes used to represent the String in various encodings: 在Swift String API中,有一种方法可以为我们提供用于以各种编码表示String的数据字节:

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

The first parameter to this method is of Type String.Encoding . 此方法的第一个参数是String.Encoding类型。 This struct Encoding has an encoding declared as: 此结构Encoding的编码声明为:

static let unicode: String.Encoding

Now suddenly the method can give me data representation of the String using the encoding .unicode 现在突然之间,该方法可以使用编码.unicode给我String数据表示.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. 它为我提供了字符串的数据表示形式,甚至以为unicode并没有为我提供如何存储它的详细信息。

Can any one tell me what am I missing here? 有人可以告诉我我在这里想念什么吗? I am really confused now. 我现在真的很困惑。

String.Encoding.unicode is the same as String.Encoding.utf16 String.Encoding.unicodeString.Encoding.utf16相同

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

The above prints: 上面的照片:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM