[Solved] swift 4 label that each time i hit the button the label shows a different word [closed]


You need to create an array first:

let creatures = ["Cat", "Dog", "Bird", "Butterfly", "Fish"]

And add an IBOutlet for your label:

@IBOutlet weak var label: UILabel!

And add an IBAction for your button:

@IBAction func updateLabelButtonTapped(_ sender: UIButton) {
    // Get the index of a random element from the array
    let randomIndex = Int(arc4random_uniform(UInt32(creatures.count)))

    // Set the text at the randomIndex as the text of the label
    label.text = creatures[randomIndex]
}

Edit:

If you wanted to show the words in order, then add a new property to your class to save the current index:

private var currentIndex = 0

And replace your IBAction with the following:

@IBAction func updateLabelButtonTapped(_ sender: UIButton) {
    label.text = creatures[currentIndex] // Set the text to the element at currentIndex in the array
    currentIndex = currentIndex + 1 == creatures.count ? 0 : currentIndex + 1 // Increment currentIndex
}

2

solved swift 4 label that each time i hit the button the label shows a different word [closed]