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


Swift Unicode.UTF16 transcodedLength(of:decodedAs:repairingIllFormedSequences:)用法及代碼示例

類型方法

transcodedLength(of:decodedAs:repairingIllFormedSequences:)

返回轉碼為 UTF-16 時給定代碼單元序列所需的 UTF-16 代碼單元數,以及指示是否發現該序列僅包含 ASCII 字符的布爾值。

聲明

static func transcodedLength<Input, Encoding>(
    of input: Input,
    decodedAs sourceEncoding: Encoding.Type,
    repairingIllFormedSequences: Bool) -> (count: Int, isASCII: Bool
)? where Input : IteratorProtocol, Encoding : _UnicodeEncoding, Input.Element == Encoding.CodeUnit

返回值

一個元組,包含編碼 input 所需的 UTF-16 代碼單元數和一個指示 input 是否僅包含 ASCII 字符的布爾值。如果 repairingIllFormedSequencesfalse 並且檢測到 ill-formed 序列,則此方法返回 nil

參數

input

要翻譯的代碼單元的迭代器,編碼為 sourceEncoding 。如果 repairingIllFormedSequencestrue ,則整個迭代器將被耗盡。否則,如果檢測到ill-formed 序列,迭代將停止。

sourceEncoding

input 的 Unicode 編碼。

repairingIllFormedSequences

通過true 來測量input 的長度,即使input 包含ill-formed 序列。每個 ill-formed 序列都被替換為 Unicode 替換字符 ("\u{FFFD}") 並按此進行測量。當遇到ill-formed 序列時,通過false 立即停止測量input

詳述

以下示例查找字符串 "Fermata 𝄐" 的 UTF-16 編碼的長度,從其 UTF-8 表示開始。


let fermata = "Fermata 𝄐"
let bytes = fermata.utf8
print(Array(bytes))
// Prints "[70, 101, 114, 109, 97, 116, 97, 32, 240, 157, 132, 144]"


let result = UTF16.transcodedLength(of: bytes.makeIterator(),
                                    decodedAs: UTF8.self,
                                    repairingIllFormedSequences: false)
print(result)
// Prints "Optional((count: 10, isASCII: false))"

可用版本

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

相關用法


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