Declared variable in viewDidLoad not found in Button - Swift 2

Asked

Viewed 62 times

0

I have an array that generates a word when loading the viewController, and saves a random position in the variable declared in viewDidLoad or before inside the class. But inside the button you cannot find the variable to receive and use the contents.

here only the code generating the random word of the array that works perfectly:

let palavra: Array = ["ABC", "DEF"]
let randomIndex = Int(arc4random_uniform(UInt32(palavra.count)))
let string = Array(palavra.characters)

then just need to make a comparison inside the button, I want to compare a typed string, comparing each letter of the string with each letter of the typed word. So I thought I’d generate an array and go through the positions by comparing.

but inside the button does not recognize the variable already created.

thank you Fernando.

  • Hello Fernando, it is easier to help you if you post the code to which you refer in the question. You can edit your question and place the relevant code without the need to create a new question.

1 answer

0

What is possibly occurring is a scope problem:

A variable (or a constant let) declared in the body of a function will only be accessible within it (in this case, from func viewDidLoad()).

By moving the declaration to a level above (at class level) you will be able to use this variable or constant within the viewDidLoad.

Something like:

class ViewController : UIViewController {    

    @IBOutlet var myButton : UIButton!

    let palavra: Array = ["ABC", "DEF"]
    let randomIndex = Int(arc4random_uniform(UInt32(palavra.count)))
    let minhaString = Array(palavra.characters)

    func viewDidLoad() {
        self.myButton.text = minhaString
       }
}

I hope I’ve helped! :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.