Last active
February 13, 2016 16:45
-
-
Save kostiakoval/7ba4fe6196efeabfed87 to your computer and use it in GitHub Desktop.
Pure Swift rangeOf String
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// MARK: - String | |
extension String { | |
func rangeOf(x: String) -> Range<Index>? { | |
return characters.rangeOf(x.characters) | |
} | |
} | |
extension String.CharacterView { | |
func rangeOf(x: String.CharacterView) -> Range<Index>? { | |
guard let first = x.first else { return nil } | |
var offset = 0 | |
var search = self | |
while !search.isEmpty { | |
guard let firtIndex = search.indexOf(first) else { return nil } | |
offset += search.startIndex.distanceTo(firtIndex) | |
search = search.suffixFrom(firtIndex) | |
if search.startsWith(x) { | |
let start = startIndex.advancedBy(offset) | |
return start..<start.advancedBy(x.count) | |
} | |
offset++ | |
search = search.dropFirst() | |
} | |
return nil | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment