0

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?

Moin Shirazi
  • 4,372
  • 2
  • 26
  • 38
Ben M.
  • 13
  • 1
  • 3
  • What are the rules for "these letters" to be "random"? Do you mean that each of the 6 letters can be any letter from A to Z? – matt Jan 23 '17 at 01:13
  • Yes, There is one letter per tile and it can be any letter A-Z. – Ben M. Jan 23 '17 at 01:14
  • Possible duplicate of [Generate random alphanumeric string in Swift](http://stackoverflow.com/questions/26845307/generate-random-alphanumeric-string-in-swift) –  Jan 23 '17 at 01:14

1 Answers1

3

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"]
Sash Sinha
  • 18,743
  • 3
  • 23
  • 40
  • Where I have this code under viewDidLoad : `randomizeAvailableLetters()` it gives me one error when I try to add the code you suggested: "Missing argument for parameter 'tileArraySize' in call" – Ben M. Jan 23 '17 at 02:15
  • `tileArraySize` is the size of your array i.e `6` call it using `randomizeAvailableLetters(tileArraySize: 6))` or just modify the function to not use the parameter if you always have an array of size 6 – Sash Sinha Jan 23 '17 at 02:19