Not really sure what you mean.
Say the word you are given is "deflects". Your first suggestion is "elect". Let's walk through it...
func isPossible(word: String) -> Bool { //1
guard var tempWord = title?.lowercased() else { return false } //2
for letter in word { //3
if let position = tempWord.firstIndex(of: letter) { //4a
tempWord.remove(at: position) //5
//6
} else {
return false //4b
}
}
return true //7
}
word
is set to "elect"
tempWord
is set to "deflects"
- we loop through every letter in "elect"
4a. if
letter
is found in word
...
- remove
letter
from tempWord
- and keep looping
4b. if
letter
is not found, return false
from isPossible
- if we make it through the loop, then
isPossible
is true
So, using "deflects" and "elects":
- is
e
found in "deflects"? yes, so remove it, leaving tempWord
as "dflects"
- is
l
found in "deflects"? yes, so remove it, leaving tempWord
as "dfects"
- is
e
found in "deflects"? yes, so remove it, leaving tempWord
as "dfcts"
- is
c
found in "deflects"? yes, so remove it, leaving tempWord
as "dfts"
- is
t
found in "deflects"? yes, so remove it, leaving tempWord
as "dfs"
- we're done looping through "elect" so return
true
We can see that even though the e
is reused in "elect", our function still works as expected.
If a letter is reused in the player's word but it doesn't appear more than once in the given word, then isPossible
will return false because at some point tempWord
will no longer contain that letter.
So if the user tries "selects", this happens:
letter tempWord
s deflect
e dflect
l dfect
e dfct
c dft
t df
s **fail**