Reputation: 13
I am trying to create a tile-based word game using swift, and I need to randomize the letters that show up on the tiles (from A-Z). I have been reading about different ways to do this, but I haven't been able to make it work for a specific variable. I currently have a variable defined:
var availableTiles: [Character]!
Since I have been working on the layouts and interface, I have only manually input letters so far just to make sure they show up properly:
func randomizeAvailableLetter() {
availableTiles = ["X", "B", "F", "H", "K", "V"]
}
As you can see, the letters that show up on the 6 tiles are just hardcoded in, but I need for these letters to be random. What would I replace the hardcoded part with in order to make the letters that show up randomized?
Upvotes: 0
Views: 4390
Reputation: 22472
You could use a function that is something like this:
func randomizeAvailableLetters(tileArraySize: Int) -> Array<String> {
let alphabet: [String] = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]
var availableTiles = [String]()
for i in 0..<tileArraySize {
let rand = Int(arc4random_uniform(26))
availableTiles.append(alphabet[rand])
}
return(availableTiles)
}
print(randomizeAvailableLetters(tileArraySize: 6)) //["X", "B", "F", "H", "K", "V"]
Upvotes: 3