2016-10-04 45 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

相關問題