2016-10-04 44 views
2
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,发现:var characters: String.CharacterViewString成员'characters'返回什么?

然而我不知道究竟是str.characters返回?它是如何,我可以列举就那么轻易,或转换它给数组或地图,但然后再打印本身甚至索引时把它打印乱码等等

我敢肯定我不明白的是因为不了解characterView。我希望有人能够向外行介绍一下它在这个问题上的作用和意义。

+1

您不仅应该查看'CharacterView'文档,还应该查看它符合的协议的文档,这些都是您正在查找的内容。例如,您可以枚举'CharacterView',因为它符合'Sequence'协议。 – Fantattitude

+0

@Fantattitude我只是重新读一遍,仍然失去了 – Honey

回答

2

str.characters返回String.CharacterView - 它提出了一个视图到字符串的字符,让您可以访问它们,而无需将内容复制到一个新的缓冲区(而做Array(str.characters)str.characters.map{...}会做到这一点)。

String.CharacterView本身是由一个String.CharacterView.Index(不透明指数型)索引,并且具有Character类型的元素(勿庸置疑)(它表示一个扩展字形集群Collection - 通常什么读取器将考虑“单字符”到是)。

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) 

它是如何把它打印这样的胡言乱语索引的时候,我可以枚举到其中,因此容易,或将其转换为一个数组或地图,但然后再打印本身甚至

您可以枚举,转换为Array和​​一个String.CharacterView只是因为这是一个Collection - 因此符合01​​,这使得for ... in循环以及使用map(_:)Array(_:) constructer,等等。

至于为什么打印出str.characters结果'乱码'是由于它根本不提供自己的自定义文本表示符合CustomStringConvertibleCustomDebugStringConvertible

+0

非常感谢你的最后一段。虽然有些线路需要我来回来。 :) – Honey

+0

@霍尼高兴地帮助:) – Hamish

相关问题