swift - 字符串成员 'characters' 返回什么?

标签 swift string character

var str = "Hello"

print(str.characters) // CharacterView(_core: Swift._StringCore(_baseAddress: Optional(0x000000011c9a68a0), _countAndFlags: 5, _owner: nil))

print(str.characters.index(of: "o")!) // Index(_base: Swift.String.UnicodeScalarView.Index(_position: 4), _countUTF16: 1)
print(Array(str.characters)) // ["H", "e", "l", "l", "o"]
print(str.characters.map{String($0)}) //["H", "e", "l", "l", "o"]

for character in str.characters{
    print(character)
}
// H
// e
// l
// l
// o

我读到this问题。我从 Swift 引用资料中查看了 String 并发现:varcharacters: String.CharacterView

但我想知道str.characters返回的到底是什么?我怎么能如此轻松地枚举它,或者>将它转换为数组或映射它,然后打印它本身,甚至在索引到它时打印出乱码

我很确定我不明白是因为不明白characterView 。我希望有人能够让外行人了解它的作用以及在这个问题中的含义。

最佳答案

str.characters返回 String.CharacterView – 它呈现字符串字符的 View ,允许您访问它们而无需将内容复制到新的缓冲区中(而执行 Array(str.characters)str.characters.map{...} 就可以做到这一点)。

String.CharacterView 本身是 Collection其索引为 String.CharacterView.Index (不透明索引类型)并且具有 Character 类型的元素(毫不奇怪) (它代表扩展的字素簇——通常读者会认为“单个字符”)。

let str = "Hello"

// indexed by a String.Index (aka String.CharacterView.Index)
let indexOfO = str.characters.index(of: "o")!

// element of type Character
let o = str.characters[indexOfO]

// String.CharacterView.IndexDistance (the type used to offset an index) is of type Int
let thirdLetterIndex = str.characters.index(str.startIndex, offsetBy: 2)

// Note that although String itself isn't a Collection, it implements some convenience
// methods, such as index(after:) that simply forward to the CharacterView
let secondLetter = str[str.index(after: str.startIndex)]

它由特殊的String.CharacterView.Index而不是例如Int索引的原因是字符可以用不同的字节长度进行编码。因此,下标可能(在非 ASCII 存储字符串的情况下)是 O(n) 操作(需要迭代编码字符串)。然而,使用 Int 进行下标自然感觉应该是一个 O(1) 操作(便宜,不需要迭代)。

str.characters[str.characters.index(str.characters.startIndex, offsetBy: n)] // feels O(n)
str.characters[n] // illegal, feels O(1)

How is it that I can enumerate into it so easily, or convert it to an array or map it but then printing it itself or even when indexed into it prints so gibberish

您可以枚举、转换为 Arraymap(_:) String.CharacterView 只是因为它是一个 Collection – 因此符合Sequence,它允许for ... in循环以及使用map(_:)Array(_:)构造函数等等。

至于为什么打印出 str.characters 会导致“乱码”,是因为它根本没有通过遵守 CustomStringConvertible 来提供自己的自定义文本表示形式。或CustomDebugStringConvertible .

关于swift - 字符串成员 'characters' 返回什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39856541/

相关文章:

Swift Firebase 按距帖子的距离排序

ios - 删除滚动条上的 NavigationBar

C++ 子字符串/字符串操作

c++ - push_back 一个字符从一个字符串到另一个字符串

ios - 如何查看iOS app document director的内容?

c# - string.Length 与 string.ToCharArray().Length

c - 为什么我的整数数组元素包含错误的值,当我在 C 中为其分配字符值时,我该如何解决这个问题?

c - 如何修改C中字符串数组中的单个字符?

C 宽字符 - 如何使用它们?

ios - 在多个收藏 View 中显示电影列表的详细 View