ios - swift 的字符串类型是否符合集合协议(protocol)?

标签 ios swift string collections protocols

在swift编程语言书中,它指出

You can use the startIndex and endIndex properties and the index(before:), index(after:), and index(_:offsetBy:) methods on any type that conforms to the Collection protocol. This includes String, as shown here, as well as collection types such as Array, Dictionary, and Set.

但是我查看了swift的string api的apple文档,并没有说明String类型符合Collection协议(protocol)

enter image description here

我一定是在这里遗漏了一些东西,但似乎无法弄清楚。

最佳答案

从 Swift 2 开始,String 不符合 Collection,只是它的各种“ View ” 像 charactersutf8utf16unicodeScalars

(这可能在未来再次改变,比较 String should be a Collection of Characters AgainString Processing For Swift 4 .)

它有 startIndexendIndex 属性和 index 方法,这些 被转发到 characters View ,如在 源代码 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)
  }


  // ...
}

关于ios - swift 的字符串类型是否符合集合协议(protocol)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43061572/

相关文章:

ios - 辅助功能顺序

ios - 如何在另一个自定义表格 View 中快速创建自定义表格 View

swift - 如何安排进入某个区域后的某个时间推送通知? swift

c - C语言如何读取包含空格的字符串

PHP/MySQL - 将字符串附加在一起以进行查询..?

iphone - 如何为 coverflow 中的 UIimage 设置 Action ?

ios - UITableViewCell 在实现 willDisplay 函数时不取消选择

iOS:应用程序打开时显示通知消息

swift - fatal error : unexpectedly found nil while unwrapping an Optional value (lldb)

JavaScript - 使用数组索引转换为字符串