Last active
August 29, 2015 14:05
-
-
Save erica/88ceabc67b4d1607c251 to your computer and use it in GitHub Desktop.
This file contains 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
// This should have worked. It doesn't work. | |
// Out of range error because the String.Index is set with regard to the smallest string at match | |
//extension String { | |
// | |
// func findIndexOf(substring : String) -> String.Index? { | |
// if countElements(self) < countElements(substring) {return nil} | |
// if countElements(substring) == 0 {return nil} | |
// if self.hasPrefix(substring) {return self.startIndex} | |
// if let recursionResults = dropFirst(self).findIndexOf(substring) { | |
// return recursionResults.successor() | |
// } else { | |
// return nil | |
// } | |
// } | |
//} | |
extension String { | |
func indexOfSubstring(substring : String) -> Int? { | |
if countElements(self) < countElements(substring) {return nil} | |
if countElements(substring) == 0 {return nil} | |
if self.hasPrefix(substring) {return 0} | |
if let recursionResults = dropFirst(self).indexOfSubstring(substring) { | |
return recursionResults + 1 | |
} else { | |
return nil | |
} | |
} | |
func findIndexOf(substring : String) -> String.Index? { | |
if let result = self.indexOfSubstring(substring) { | |
return advance(self.startIndex, result) | |
} else { | |
return nil | |
} | |
} | |
} | |
var x = "Hello, World" | |
println(x.findIndexOf("World")) | |
let clarus = "🐶🐮" | |
println(clarus.findIndexOf("🐮")) | |
println(clarus.startIndex) // prints 0 | |
println(advance(clarus.startIndex, 1)) // prints 2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment