Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

enter image description here

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

like image 635
Thor Avatar asked Oct 16 '25 07:10

Thor


2 Answers

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


  // ...
}
like image 54
Martin R Avatar answered Oct 19 '25 01:10

Martin R


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.

like image 38
Jyoti Avatar answered Oct 19 '25 01:10

Jyoti