當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Swift String.UnicodeScalarView用法及代碼示例

結構

String.UnicodeScalarView

將字符串內容視為 Unicode 標量值集合的視圖。

聲明

@frozen struct UnicodeScalarView

概述

您可以使用字符串的unicodeScalars 屬性訪問字符串的 Unicode 標量值視圖。 Unicode 標量值是 21 位代碼,是 Unicode 的基本單位。每個標量值由一個Unicode.Scalar 實例表示,相當於一個 UTF-32 代碼單元。


let flowers = "Flowers 💐"
for v in flowers.unicodeScalars {
    print(v.value)
}
// 70
// 108
// 111
// 119
// 101
// 114
// 115
// 32
// 128144

字符串中可見的某些字符由多個 Unicode 標量值組成。在這種情況下,字符串的 unicodeScalars 視圖包含比字符串本身更多的元素。


let flag = "🇵🇷"
for c in flag {
    print(c)
}
// 🇵🇷


for v in flag.unicodeScalars {
    print(v.value)
}
// 127477
// 127479

您可以使用 String 類型的 init(_:) 初始化程序將 String.UnicodeScalarView 實例轉換回字符串。


let favemoji = "My favorite emoji is 🎉"
if let i = favemoji.unicodeScalars.firstIndex(where: { $0.value >= 128 }) {
    let asciiPrefix = String(favemoji.unicodeScalars[..<i])
    print(asciiPrefix)
}
// Prints "My favorite emoji is "

可用版本

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

相關用法


注:本文由純淨天空篩選整理自apple.com大神的英文原創作品 String.UnicodeScalarView。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。