If you really need to access a character at a specific index, you can use the advance function with the startIndex of the string:
var sameplace = 0
for n in 0..<(word1.utf16Count){
if word1[advance(word1.startIndex, n)] == word2[advance(word2.startIndex, n)]{
sameplace += 1
}
}
However, this is terribly inefficient because it iterates to n for every iteration through the for loop. It is also not ideal to assume the utf16 count is correct.
Instead, you can iterate the String.Indexs more manually:
var sameplace = 0
var index1 = word1.startIndex
var index2 = word2.startIndex
do {
if word1[index1] == word2[index2]{
sameplace += 1
}
index1 = index1.successor()
index2 = index2.successor()
}
while(index1 != word1.endIndex && index2 != word2.endIndex);
You could also potentially make use of a templated function to help you iterate over two sequences (this will allow any Sequence, not just strings):
func iterateTwo<S: Sequence>(seq1: S, seq2: S, block: (S.GeneratorType.Element, S.GeneratorType.Element) -> ()) {
var gen1 = seq1.generate()
var gen2 = seq2.generate()
while (true) {
var possibleElement1 = gen1.next()
var possibleElement2 = gen2.next()
if possibleElement1 && possibleElement2 {
block(possibleElement1!, possibleElement2!)
}
else {
break
}
}
}
Then you can simply do:
var sameplace = 0
iterateTwo(word1, word2) { (char1, char2) in
if char1 == char2 {
sameplace += 1
}
}
sameplace.