Преобразование ответа Тима в Swift 4:
extension NSString {
open func ranges(of searchString: String) -> [NSRange] {
var ranges = [NSRange]()
var searchRange = NSRange(location: 0, length: self.length)
var range: NSRange = self.range(of: searchString)
while range.location != NSNotFound {
ranges.append(range)
searchRange = NSRange(location: NSMaxRange(range), length: self.length - NSMaxRange(range))
range = self.range(of: searchString, options: [], range: searchRange)
}
return ranges
}
}
Также сделал это в примитиве Swift's String:
extension String {
func ranges(of substring: String, options: CompareOptions = [], locale: Locale? = nil) -> [Range<Index>] {
var ranges: [Range<Index>] = []
while let range = self.range(of: substring, options: options, range: (ranges.last?.upperBound ?? self.startIndex)..<self.endIndex, locale: locale) {
ranges.append(range)
}
return ranges
}
}