user3004698 user3004698 - 5 months ago 34x
Swift Question

Is there an index type for Swift String?

From what I've learned I understand that Swift strings cannot be indexed by integer values. But I'm curious what is the type of the index, or is there any. I wrote the following code in Xcode palyground:

let greeting = "Hello! Tom"
let index = greeting.startIndex

By tap key and click on the index value, the Xcode inferred that the type of index is Index (please see the attached figure below). However, when I changed the second line to

let index: Index = greeting.startIndex

I've got two error warnings from the Xcode

error: use of undeclared type 'Index'
error: could not infer type for 'index'

Isn't Xcode told me that it inferred the index type is Index, why there comes the error when I explictly declared the type? Can someone explain that to me?

Xcode type infer


There is an Index for String types:

extension String {
    public typealias Index = String.CharacterView.Index
    /// The position of the first `Character` in `self.characters` if
    /// `self` is non-empty; identical to `endIndex` otherwise.
    public var startIndex: Index { get }
    /// The "past the end" position in `self.characters`.
    /// `endIndex` is not a valid argument to `subscript`, and is always
    /// reachable from `startIndex` by zero or more applications of
    /// `successor()`.
    public var endIndex: Index { get }
    /// Access the `Character` at `position`.
    /// - Requires: `position` is a valid position in `self.characters`
    ///   and `position != endIndex`.
    public subscript (i: Index) -> Character { get }

Declaring Index is ambiguous in the current context. Use String.Index to explicitly refer to the typealias defined in the String extension:

let index: String.Index = greeting.startIndex // 0

If you really want to go crazy, you could create another typealias at the top level scope:

public typealias Index = String.Index
let index: Index = greeting.startIndex // 0

Not sure I would recommend this though.