Home > Mobile >  Subscript 'subscript(_:)' requires that 'String.Index' conform to 'RangeExp
Subscript 'subscript(_:)' requires that 'String.Index' conform to 'RangeExp

Time:03-04

I have a simple function:

private func formatted(phoneNumber: String, mask: String) -> String {
    var output = ""
    var index = phoneNumber.startIndex
    for character in mask where index < phoneNumber.endIndex {
        if character == "_" {
            output  = phoneNumber[index] //hers is an error
            index = phoneNumber.index(after: index)
        } else {
            output  = String(character)
        }
    }
    return output
}

What should I do to fix that error?

How do I call it?

formatted(phoneNumber: "12345678", mask: " ___ __ ___") // " 123 45 678"

CodePudding user response:

Notice that the string subscript returns a Character, but = can only be used to add a sequence of characters to a string:

static func  = <Other>(lhs: inout String, rhs: Other) where Other : Sequence, Character == Other.Element

Hence Swift resolves the subscript to the subscript that takes a range and returns a Substring, and says that index is not a range.

You can create a CollectionOfOne/String/Array out of the character and then use = to concatenate

output  = CollectionOfOne(phoneNumber[index])

or just:

output.append(phoneNumber[index])

The same thing applies to the else branch too :)

  • Related