@H_502_0@
@H_502_0@
for codeUnit in language.utf8
{
print("utf8:\(codeUnit) ",terminator: "")
}
print("\n")
for codeUnit in language.utf16
{
print("utf16:\(codeUnit) ",terminator: "")
}
结果:
utf8:83 utf8:119 utf8:105 utf8:102 utf8:116 utf8:232 utf8:175 utf8:173 utf8:232 utf8:168 utf8:128
utf16:83 utf16:119 utf16:105 utf16:102 utf16:116 utf16:35821 utf16:35328
@H_502_0@@H_502_0@为了方便使用,我们可以扩展String的属性:
//自定义字符串长度的计算属性 extension String { var length: Int { return self.characters.count } }
language.length //returns 7
@H_502_0@我们再看看官方的例子,说的比较清楚: @H_502_0@
@H_502_0@
@H_502_0@这是一个混有不同类型字符的例子,狗头是表情字符,占用4个字节。 @H_502_0@
@H_502_0@1. utf8 表达: @H_502_0@
@H_502_0@
@H_502_0@
@H_502_0@可以看到占用了10个字节,即dogString.utf8.count == 10 @H_502_0@每个单位是 UInt8 类型
@H_502_0@
@H_502_0@2. utf16表达:dogString.utf16.count == 6
每个单位是 unsigned int16类型
一个表情符号需要2个UInt16表示。
@H_502_0@@H_502_0@3. unicodeScalar 标量表示 @H_502_0@dogString.unicodeScalars.count == 5
@H_502_0@每个单位是UnicodeScalar,占用UInt32的内存,持有21bit的数据。 @H_502_0@Each
UnicodeScalar
has avalue
property that returns the scalar’s 21-bit value,represented within aUInt32
value。@H_502_0@
@H_502_0@这种表达方式最接近我们所见到的内容。 @H_502_0@
@H_502_0@参考链接: @H_502_0@Swift_Programming_Language:StringsAndCharacters