Going through Swift algorithms including the brute force string search i.e.: https://github.com/raywenderlich/swift-algorithm-club/tree/master/Brute-Force%20String%20Search
The output is said to be 7
Now actually the output is (String.Index?) - and although I can subscript with that I want to actually see the value - 7.
The code is
extension String {
func indexOf(_ pattern: String) -> String.Index? {
for i in self.characters.indices {
var j = i
var found = true
for p in pattern.characters.indices{
if j == self.characters.endIndex || self[j] != pattern[p] {
found = false
break
} else {
j = self.characters.index(after: j)
}
}
if found {
return i
}
}
return nil
}
}
I've looked at converting String.Index to range in the documentation and here: Convert String.Index to Int or Range<String.Index> to NSRange but the answer to that question is old and does not present an answer (if such an answer exists) for Swift 4.
Distance to also does not work as in:
let s = "Hello, World"
let res = ( s.indexOf("World") )
let index: Int = s.startIndex.distance(to: res)
print (s[res!])
and the existing OffsetIndexableCollection does not even compile
so how can I convert
s.indexOf("World")
to "7" where s is "Hello, World"