RemoveAtIndex crash from swift array

后端 未结 5 660
半阙折子戏
半阙折子戏 2021-01-25 20:43

I have an array of letters, and want to match the characters against the letters and then do something to that letter (in this case turn it yellow) and then remove that matched

5条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-25 21:35

    just fixed it after reading the SDs post here: Swift buttons hidden fatal error: Array index out of range

    I updated this question in case it helps anyone else.

    I added an if statement to check the index was still in range. Not really sure why this works but it does :-)

    var letters = Array(word1) // [r,a,n,d,o,m,n,e,s,s]
    var characters = Array(specialLetters) // [n,e,s,s]
    
    // delete the special letters
    for (index, element) in enumerate(characters) {
         if letter == element {
               tile.letterLabel.textColor = UIColor.yellowColor()
    
               // remove that character from the array so can't be matched twice.  
               // first check that the index is still in range. 
               if index < characters.count { // added this if statement
                    characters.removeAtIndex(index)
               }
         }
    }
    

提交回复
热议问题