我有这个代码,我称之为“检查功能”功能。我没有在我的应用程序中使用任何线程,如果它有利于我的应用程序的性能,我很乐意使用。
“检查功能”比我预期的花费更多时间。完成执行需要30多秒。我不能在我的应用程序中等待那么久。这在游戏中期并不好。
有人帮我在这里重写函数,以便我可以更快地执行它。一些函数式编程方式,如果可能的话。
func returnCharactersFromAFourLetterString(inputString : String) -> (First : Character,Second : Character, Third : Character, Fourth : Character)
{
return (inputString[advance(inputString.startIndex, 0)],inputString[advance(inputString.startIndex, 1)],inputString[advance(inputString.startIndex, 2)],inputString[advance(inputString.startIndex, 3)])
}
func checkingWords(userEnteredWord : String)
{
var tupleFourLetters = self.returnCharactersFromAFourLetterString(userEnteredWord)
var firstLetter = String(tupleFourLetters.First)
var secondLetter = String(tupleFourLetters.Second)
var thirdLetter = String(tupleFourLetters.Third)
var fourthLetter = String(tupleFourLetters.Fourth)
var mainArrayOfWords : [String] = [] // This array contains around 0.2 million words
var userEnteredTheseWords : [String] = [] // This array contains less than 10 elements
// Check for FirstLetter
for index in 0..<array.count // Array of Letters as Strings , count = 200
{
var input = array[index]
var firstWord = "\(input)\(secondLetter)\(thirdLetter)\(fourthLetter)"
var secondWord = "\(firstLetter)\(input)\(thirdLetter)\(fourthLetter)"
var thirdWord = "\(firstLetter)\(secondLetter)\(input)\(fourthLetter)"
var fourthWord = "\(firstLetter)\(secondLetter)\(thirdLetter)\(input)"
if !contains(userEnteredTheseWords, firstWord) && !contains(userEnteredTheseWords, secondWord) && !contains(userEnteredTheseWords, thirdWord) && !contains(userEnteredTheseWords, fourthWord)
{
if contains(mainArrayOfWords, firstWord )
{
self.delegate?.wordMatchedFromDictionary(firstWord)
return
}
else if contains(mainArrayOfWords, secondWord)
{
self.delegate?.wordMatchedFromDictionary(secondWord)
return
}
else if contains(mainArrayOfWords, thirdWord)
{
self.delegate?.wordMatchedFromDictionary(thirdWord)
return
}
else if contains(mainArrayOfWords, fourthWord)
{
self.delegate?.wordMatchedFromDictionary(fourthWord)
return
}
}
if index == array.count - 1
{
self.delegate?.wordMatchedFromDictionary("NoWord")
}
}
}
这个函数的输入是一个四个字母的单词,在这个函数中我通过循环遍历200个字母来改变每个字母,并在mainArray中检查mainArray中是否存在任何这些改变的单词。如果存在,则返回该单词,否则返回NoWord。总而言之,我们可以看到我们检查包含(mainArray,word)的东西大约800次,我认为这是消耗更多时间的行,因为mainArray包含20万字。
答案 0 :(得分:2)
使用词典查找内容。
当您测量时间时,尤其是使用Swift代码时,请测量发布版本,而不是调试版本。另一方面,测量能够运行代码的最慢设备。