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?
CodePudding user response:
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" {
/* ... */
}