Skip to content

Commit 7cf6a49

Browse files
committed
Fix replace algorithm updating of ranges.
1 parent 1f019a6 commit 7cf6a49

1 file changed

Lines changed: 6 additions & 4 deletions

File tree

Aztec/Classes/Extensions/NSMutableAttributedString+ReplaceOcurrences.swift

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -32,17 +32,19 @@ extension NSMutableAttributedString {
3232

3333
assert(!replacementString.contains(stringToFind),
3434
"Allowing the replacement string to contain the original string would result in a ininite loop.")
35-
36-
let swiftUTF16Range = string.utf16.range(from: range)
35+
let rangeDifference = (replacementString as NSString).length - (stringToFind as NSString).length
36+
var swiftUTF16Range = string.utf16.range(from: range)
3737
var swiftRange = string.range(from: swiftUTF16Range)
38-
3938
while let matchRange = string.range(of: stringToFind, options: [], range: swiftRange, locale: nil) {
4039
let matchNSRange = string.utf16NSRange(from: matchRange)
4140

4241
replaceCharacters(in: matchNSRange, with: replacementString)
4342

4443
// Since the new string may invalidate the initial swift range, we want to update it.
45-
swiftRange = swiftRange.lowerBound ..< string.index(matchRange.lowerBound, offsetBy: replacementString.count)
44+
// And because the string that backs the NSAttributeString will change after the replace we need to recalculate the index from scratch
45+
let updatedRange = range.extendedRight(by: rangeDifference)
46+
swiftUTF16Range = string.utf16.range(from: updatedRange)
47+
swiftRange = string.range(from: swiftUTF16Range)
4648
}
4749
}
4850
}

0 commit comments

Comments
 (0)