Variable declared in viewDidLoad is not found in Button - Swift 2

0

I have an array that generates a word by loading viewController , and saves a random position in the variable declared in viewDidLoad or before within the class. But inside the button does not find the variable to receive and use the content.

here is just the code generating the random word from the array that works perfectly:

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

Then I just need to make a comparison inside the button, I want to compare a typed string by comparing each letter of the string with each letter of the typed word. So I thought about generating an array and traversing the positions by comparing.

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

Thank you Fernando.

    
asked by anonymous 11.10.2015 / 22:15

1 answer

0

What is possibly occurring is a scope problem:

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

By moving the statement to a level above (at the class level) you will be able to use this variable or constant within 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 have helped! :)

    
28.10.2015 / 22:13