2017-03-28 41 views
1

在迅速的編程語言的書,它指出做swift的字符串類型是否符合收集協議?在offsetBy :)方法:

您可以使用startIndex和endIndex的性質和 指數(:)指數(:)後,和索引(前_任何符合Collection協議的 類型。其中包括字符串, (如此處所示)以及集合類型,例如Array,Dictionary, 和Set。

不過,我已經檢查了迅速的串API,蘋果文檔不表明String類型符合Collection協議

enter image description here

我必須在這裏失去了一些東西,但不能似乎弄明白了。

回答

3

作爲夫特2,String不符合Collection,只有它的各種 「意見」 像charactersutf8,或utf16unicodeScalars

(這可能會在未來再次發生變化,在 String Processing For Swift 4比較 String should be a Collection of Characters Again。)

startIndexendIndex屬性和index方法雖然,這些 被轉發到characters來看,由於中可以看到 源代碼 StringRangeReplaceableCollection.swift.gyb

extension String { 
    /// The index type for subscripting a string. 
    public typealias Index = CharacterView.Index 


    // ... 

    /// The position of the first character in a nonempty string. 
    /// 
    /// In an empty string, `startIndex` is equal to `endIndex`. 
    public var startIndex: Index { return characters.startIndex } 


    /// A string's "past the end" position---that is, the position one greater 
    /// than the last valid subscript argument. 
    /// 
    /// In an empty string, `endIndex` is equal to `startIndex`. 
    public var endIndex: Index { return characters.endIndex } 

    /// Returns the position immediately after the given index. 
    /// 
    /// - Parameter i: A valid index of the collection. `i` must be less than 
    /// `endIndex`. 
    /// - Returns: The index value immediately after `i`. 
    public func index(after i: Index) -> Index { 
    return characters.index(after: i) 
    } 


    // ... 
} 
+0

喜馬丁!很高興再次見到你,希望你有一個美好的一天:) – Thor

+0

你的答案永不停止令我驚歎!它是如此完整和知情!如果我問你用什麼方法尋找資源並解決問題,你介意嗎?因爲如果我自己,我需要幾天才能找到相關的資源。 – Thor

相關問題