Search code examples
iosswiftgoto

Other alternatives that can be used for goto swift


Here is my code:

func deneme() {

    var buttons: [UIButton] = [buttonA,buttonB,buttonC,buttonD,buttonE]

    let randomNumber = Int(arc4random_uniform(UInt32(buttons.count)))
    let button = buttons.remove(at: randomNumber)

    if button.titleLabel?.text == cevapLabel.text {

    }
    else {
        button.isHidden = true
    }
}

I want to use these codes in if statement. if swift had goto, i could write a code like:

    var buttons: [UIButton] = [buttonA,buttonB,buttonC,buttonD,buttonE]
    A:
    let randomNumber = Int(arc4random_uniform(UInt32(buttons.count)))
    let button = buttons.remove(at: randomNumber)

    if button.titleLabel?.text == cevapLabel.text {
       goto A
    }
    else {
      button.isHidden = true
    }

purpose of code: hiding buttons. If the text of the buttons in the array is the equal to cevapLabel.text, the random code should restart.


Solution

  • You can use repeat-while:

    var buttons: [UIButton] = [buttonA,buttonB,buttonC,buttonD,buttonE]
    var currentButton: UIButton?
    repeat {
        let randomNumber = Int(arc4random_uniform(UInt32(buttons.count)))
        currentButton = buttons.remove(at: randomNumber)
    } while currentButton?.titleLabel?.text == cevapLabel.text
    
    currentButton?.isHidden = true