Search code examples
iosswiftstringcollectionsprotocols

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.


Solution

  • 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)
      }
    
    
      // ...
    }