Search code examples
iosswiftuibuttonibaction

Error? Reading variable inside IBAction Button


I have an IBAction that needs to read from a variable. However, when placing the variable outside of the viewDidLoad I receive the error

Cannot use instance member 'animal' within property initializer; property initializers run before 'self' is available

My code is as follows. When I move the variable back inside the viewDidLoad the error states that animalName is undeclared

var animalName = (String(format: "%03d", animal.speciesId!))

@IBAction func megaKeyIBO(_ sender: Any) {
    animalName = (String(format: "%03d", animal.speciesId!)) + "-merg"
}

override func viewDidLoad() {
    super.viewDidLoad()

    //variable was originally here before moving to top
    var animalName = (String(format: "%03d", animal.speciesId!))
}

Solution

  • This happens because you're trying to initialize your animalName before your property animal.speciesId! has been initialized. A simply way to solve would be this:

    var animalName: String!
    
    @IBAction func megaKeyIBO(_ sender: Any) {
        animalName = (String(format: "%03d", animal.speciesId!)) + "-merg"
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
        // Initialize on viewDidLoad
        animalName = (String(format: "%03d", animal.speciesId!))
    }