Finn Reynolds Finn Reynolds - 1 month ago 16
iOS Question

Hangman Program

I'm working on a Hangman single view application game on iOS and I keep on getting stuck on the "letterButton" code. What I intended to do was to replace the dashes generated in

viewDidLoad
function with what the user will input through the letter buttons (all of the letter buttons are grouped under
letterButton
).

I tried replacing the dash array with the letter array but it simply tells me that the letter array is simply too big. I tried converting letter array to a string and then replacing the dash array with that but that didn't work either. So now I'm stuck and I do not know what to do to replace the dash array with letter inputs.

Please help (here is my code; please ignore the
dashArray [n]
part that was simply me trying desperately):

class ViewController: UIViewController {
@IBOutlet var letters: [UIButton]!
var wordArray: [String] = ["cat", "dog", "hamster", "lizard"]
var letterArray: [String] = ["Q","W","E","R","T","Y","U","I","O","P","A","S","D","F","G","H","J","K","L","Z","X","C","V","B","N","M"]
var randomValue: Int = 0
var word: String = ""

@IBOutlet weak var wordLabel: UILabel!

override func viewDidLoad()
{
randomValue = Int(arc4random_uniform(UInt32(wordArray.count)))
word = wordArray[randomValue]
letterArray = Array(arrayLiteral: word)

let amount = word.characters.count
let dashArray = Array(count: amount, repeatedValue: "_")
let dashString = dashArray.joinWithSeparator(" ")

wordLabel.text = dashString

super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

@IBAction func letterButton(sender: UIButton)
{
let amount = word.characters.count

var dashArray = Array(count: amount, repeatedValue: "_")

dashArray [0] =
dashArray [1] =
dashArray [2] =
dashArray [3] =
dashArray [4] =
dashArray [5] =
dashArray [6] =

let dashString = dashArray.joinWithSeparator(" ")
wordLabel.text = dashString
}

@IBAction func resetButton(sender: UIButton)
{
let amount = word.characters.count
let dashArray = Array(count: amount, repeatedValue: "_")
let dashString = dashArray.joinWithSeparator(" ")

wordLabel.text = dashString
}
}

Answer

If I've got you right, you need to take a letter from a tapped button and replace a corresponding dash with this letter.

@IBAction func letterButton(sender: UIButton)
{
    guard let letterIndex = letters.indexOf(sender) else { return }

    let letter = letterArray[letterIndex]

    var dashString = wordLabel.text
    dashString[letterIndex] = letter
    wordLabel.text = dashString
}