简体   繁体   中英

does swift's string type conform to collection protocol?

In the swift programming language book, it states

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.

However, I have checked the apple documentation on swift's string api, which does not indicate that String type conform to Collection protocol

在此处输入图像描述

I must be missing something here, but can't seem to figure it out.

As of Swift 2, String does not conform to Collection , only its various "views" like characters , utf8 , utf16 or unicodeScalars .

(This might again change in the future, compare String should be a Collection of Characters Again in String Processing For Swift 4 .)

It has startIndex and endIndex properties and index methods though, these are forwarded to the characters view, as can be seen in the source code 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)
  }


  // ...
}

Strings are collections again. This means you can reverse them, loop over them character-by-character, map() and flatMap() them, and more. For example:

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) } This change was introduced as part of a broad set of amendments called the String Manifesto.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM