Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Subscript 'subscript(_:)' requires that 'String.Index' conform to 'RangeExpression'

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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 🙂

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading