I get an error when I try to access the matches of a regex search, but I can't find where my error is.
Here is the code I'm using in a playground.
import Foundation
let sentence = "There are no strangers, only friends you have not met yet."
let search = "i"
let replace = "ui"
var transformed = sentence
let range = NSRange(transformed.startIndex..., in: transformed)
let regex = try NSRegularExpression(pattern: search, options: [])
let matches = regex.matches(in: transformed, options: [], range: range)
let numberOfMatches = regex.numberOfMatches(in: transformed, options: [], range: range)
matches.forEach({ match in
if match.numberOfRanges > 0 {
guard let subrange = Range(match.range(at: 1), in: transformed) else {
return
}
//let substring = transformed[subrange]
transformed.replaceSubrange(subrange, with: replace)
}
})
When I run the code, I get an error at the "matches.forEach" line. I can't see where my error is. Could someone help me?
(Swift 5.4.2, macOS 11.5.2 20G95, Xcode 12.5.1 12E507)