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

4
在Swift编程语言书中,它指出:您可以在任何符合集合协议的类型上使用startIndex和endIndex属性,以及index(before:)、index(after:)和index(_:offsetBy:)方法。 这包括String(如此处所示),以及诸如Array、Dictionary和Set等集合类型。
但是,我已经检查了Swift字符串API的苹果文档,它并没有表明String类型符合Collection协议。

enter image description here

我可能漏掉了什么,但似乎无法弄清楚。

2个回答

4
自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)
  }


  // ...
}

嗨,马丁!很高兴再次见到你,希望你今天过得愉快 :) - Thor
你的回答让我惊叹不已!它是如此完整和详细!如果我独自解决问题,我需要花费数天才能找到相关资源。你介意告诉我你用来寻找资源和解决问题的方法吗? - Thor

1

字符串是一组字符的集合。这意味着您可以对它们进行反转,逐个字符地循环遍历、映射(map())和扁平化(flatMap())等操作。例如:

let quote = "It is a truth universally acknowledged that new Swift versions bring new features." let reversed = quote.reversed()

for letter in quote { print(letter) } 这个变化是作为一个广泛的修改集合——字符串宣言的一部分引入的。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接