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?
extension String {
public subscript(_ idx: Int) -> Character {
self[self.index(self.startIndex, offsetBy: idx)]
}
}
Now you able to use "asdf"[4]
syntax like in other languages:)
print( "asdffdsa"[0] ) // a
print( "asdffdsa"[1] ) // s
print( "asdffdsa"[2] ) // d
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" {
/* ... */
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.