当前位置: 首页>>编程示例 >>用法及示例精选 >>正文


Swift String.UTF8View用法及代码示例

结构

String.UTF8View

将字符串内容视为 UTF-8 代码单元集合的视图。

声明

@frozen struct UTF8View

概述

您可以使用字符串的utf8 属性访问字符串的 UTF-8 代码单元视图。字符串的 UTF-8 视图将字符串的 Unicode 标量值编码为 8 位整数。


let flowers = "Flowers 💐"
for v in flowers.utf8 {
    print(v)
}
// 70
// 108
// 111
// 119
// 101
// 114
// 115
// 32
// 240
// 159
// 146
// 144

字符串的 Unicode 标量值最长可达 21 位。要使用 8 位整数表示这些标量值,通常需要多个 UTF-8 代码单元。


let flowermoji = "💐"
for v in flowermoji.unicodeScalars {
    print(v, v.value)
}
// 💐 128144


for v in flowermoji.utf8 {
    print(v)
}
// 240
// 159
// 146
// 144

在 Unicode 标量值的编码表示中,第一个之后的每个 UTF-8 代码单元称为 continuation byte

UTF8View 元素匹配编码的 C 字符串

Swift 通过让您将 String 实例作为 Int8UInt8 指针传递给函数来简化与 C 字符串 API 的互操作。当您使用 String 调用 C 函数时,Swift 会自动创建一个 UTF-8 代码单元的缓冲区并将指针传递给该缓冲区。该缓冲区的代码单元与字符串的 utf8 视图中的代码单元匹配。

以下示例使用 C strncmp 函数来比较两个 Swift 字符串的开头。 strncmp 函数采用两个 const char* 指针和一个整数,指定要比较的字符数。由于字符串在第 14 个字符之前都是相同的,因此仅比较这些字符会导致返回值 0


let s1 = "They call me 'Bell'"
let s2 = "They call me 'Stacey'"


print(strncmp(s1, s2, 14))
// Prints "0"
print(String(s1.utf8.prefix(14))!)
// Prints "They call me '"

将比较的字符数扩展到 15 个包括不同的字符,因此返回非零结果。


print(strncmp(s1, s2, 15))
// Prints "-17"
print(String(s1.utf8.prefix(15))!)
// Prints "They call me 'B"

可用版本

iOS 8.0+, iPadOS 8.0+, macOS 10.10+, Mac Catalyst 13.0+, tvOS 9.0+, watchOS 2.0+

相关用法


注:本文由纯净天空筛选整理自apple.com大神的英文原创作品 String.UTF8View。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。