Controller has no member variable

I have a game I'm working on which uses the UIAlertController to change a String variable for the player's gender pronouns.



class GameViewController: UIViewController {
    
    var hes=""
    
    var TapChat = 0
    
    
    let gender = UIAlertController(title: "About Me", message: "I am a...", preferredStyle: .alert)
    
   let female = UIAlertAction(title: "Female", style:.default) { (female) in
    self.hes="she's"      //ERROR: Value of type '(GameViewController) -> () -> GameViewController' has no member 'hes'
}
//I have the alert presented within a switch case inside a UITapGestureRecognizer IBAction func {{
            
        self.gender.addAction(self.female)
            self.present(gender, animated:true, completion:nil)



//case and IBAction func end }} 
    
    
    override func viewDidLoad() {
        
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }
    
}

Accepted Reply

In Swift, using `self` in an initializer of instance property causes disastrous result.

You should better avoid `self` in the initial value of instance properties.


In your case, you should instantiate the UIAlertController at each time you want to show it.

class GameViewController: UIViewController {
      
    var hes=""
      
    var tapChat = 0
      
    func someAction() {
        //...
        let gender = UIAlertController(title: "About Me", message: "I am a...", preferredStyle: .alert)
           
        let female = UIAlertAction(title: "Female", style:.default) { (female) in
            self.hes="she's"
        }
        gender.addAction(female)
        self.present(gender, animated:true, completion:nil)
        //...
    }
}

Replies

Forgot to mention the fact I have an error:

⚠ Value of type '(GameViewController) -> () -> GameViewController' has no member 'hes'


I'm pretty new to Swift so I need help

Have you checked you don't miss a closing curly brace somewhere ?

In Swift, using `self` in an initializer of instance property causes disastrous result.

You should better avoid `self` in the initial value of instance properties.


In your case, you should instantiate the UIAlertController at each time you want to show it.

class GameViewController: UIViewController {
      
    var hes=""
      
    var tapChat = 0
      
    func someAction() {
        //...
        let gender = UIAlertController(title: "About Me", message: "I am a...", preferredStyle: .alert)
           
        let female = UIAlertAction(title: "Female", style:.default) { (female) in
            self.hes="she's"
        }
        gender.addAction(female)
        self.present(gender, animated:true, completion:nil)
        //...
    }
}

Thanks for the help! 🙂