swift的字符串类型是否符合收集协议?

时间:2017-03-28 05:53:21

标签: ios swift string collections protocols

在swift编程语言书中,它说明了

  

您可以使用startIndex和endIndex属性和   索引(前:),索引(后:)和索引(_:offsetBy :)上的方法   符合Collection协议的类型。这包括String,   如此处所示,以及集合类型,如Array,Dictionary,   和Set。

但是,我已经检查了swift的字符串api上的apple文档,这并不表示String类型符合Collection协议

enter image description here

我必须在这里遗漏一些东西,但似乎无法弄明白。

1 个答案:

答案 0 :(得分:3)

从Swift 2开始,String不符合Collection,只符合其各种"视图" 例如charactersutf8utf16unicodeScalars

(这可能会在将来再次发生变化,比较 String should be a Collection of Characters Again in String Processing For Swift 4。)

它有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)
  }


  // ...
}