Skip to content

Instantly share code, notes, and snippets.

@txaiwieser
Created August 30, 2016 15:15
Show Gist options
  • Save txaiwieser/9dfd41c8df1f69082e04f32a6f9e2a4f to your computer and use it in GitHub Desktop.
Save txaiwieser/9dfd41c8df1f69082e04f32a6f9e2a4f to your computer and use it in GitHub Desktop.
import UIKit
/// 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 []
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment