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(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead in swift

This is my code:

let textRange = UETextRange(charIndex: i, length: l - i)
for j in textRange.charIndex...getCharIndexAfterEndOfRange(range: textRange) {   
    if String(initialText[j - 1]) == "\n" { //error here
        hits += 1
        let hitIndex = attributeRange.index + (hits - 1)
        if hitIndex <= paragraphStyles.count {
            let charIndex = paragraphStyles[hitIndex].charIndex
        }
    }
}

How do I solve this error?

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

>Solution :

Accessing elements of a String in Swift works slightly differently to most languages. Swift’s String subscript expects a String.Index (not an Int), as shown in the documentation:

@inlinable public subscript(i: String.Index) -> Character { get }

What we want to do instead is get the startIndex, offset that by the integer index we want, and then get that index from the string. Fixed code:

let char = initialText[initialText.index(initialText.startIndex, offsetBy: j - 1)]

if char == "\n" {
    /* ... */
}
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