Вот рабочая версия Swift 3 для NSRange, Range, String и NSString! Наслаждайтесь:)
/// All ranges using NSString and NSRange
/// Is usually used together with NSAttributedString
extension NSString {
public func ranges(of searchString: String, options: CompareOptions = .literal, searchRange: NSRange? = nil) -> [NSRange] {
let searchRange = searchRange ?? NSRange(location: 0, length: self.length)
let subRange = range(of: searchString, options: options, range: searchRange)
if subRange.location != NSNotFound {
let nextRangeStart = subRange.location + subRange.length
let nextRange = NSRange(location: nextRangeStart, length: searchRange.location + searchRange.length - nextRangeStart)
return [subRange] + ranges(of: searchString, options: options, searchRange: nextRange)
} else {
return []
}
}
}
/// All ranges using String and Range<Index>
/// Is usually used together with NSAttributedString
extension String {
public func ranges(of searchString: String, options: CompareOptions = [], searchRange: Range<Index>? = nil ) -> [Range<Index>] {
if let range = range(of: searchString, options: options, range: searchRange, locale: nil) {
let nextRange = range.upperBound..<(searchRange?.upperBound ?? endIndex)
return [range] + ranges(of: searchString, searchRange: nextRange)
} else {
return []
}
}
}