Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Swift String : rangesOf substrings
extension String {
func ranges(of subString: String) -> [NSRange] {
var result: [NSRange] = []
var start = startIndex
while let range = range(of: subString, options: .literal, range: start..<endIndex) {
let startPos = self.distance(from: self.startIndex, to: range.lowerBound)
let endPos = self.distance(from: self.startIndex, to: range.upperBound)
result.append(NSMakeRange(startPos, (endPos - startPos)))
start = range.upperBound
return result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment