3

I just converted to Swift 4 and am now getting the following error: Cannot subscript a value of type 'String.UnicodeScalarView' with an index of type 'CountableRange' (aka 'CountableRange')

The lines of code are:

extension AppInvite.PromoCode {
    fileprivate static func truncate(string: String) -> String {
    let validCharacters = CharacterSet.alphanumerics
    let cleaned = string.unicodeScalars.filter {
        validCharacters.contains(UnicodeScalar(UInt16($0.value))!)
    }

    let range = 0 ..< min(10, cleaned.count)
    let characters = cleaned[range].map(Character.init)
    return String(characters)
  }
}

How can I correct it?

0

1 Answer 1

5

You are using a CountableRange<Int> but to access to the characters of a String you must use CountableRange<String.Index>:

let range = cleaned.startIndex..<min(cleaned.index(cleaned.startIndex, offsetBy: 10), cleaned.endIndex)

That's because in Swift, String type has an index type of String.Index and not of Int.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.