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


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:)。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。