程序范围:如何跟踪 swift 中的变量?

scope of the program: how to keep track of a variable in swift?

我是 swift 的新手,我正在尝试了解如何初始化变量并跟踪它。在这个程序中,我有一个名为 number 的变量,我在程序的开头初始化它,在结尾处初始化一个函数。我怎样才能保留我在函数中的 number 的值,直到它到达按钮,因为现在,每次我是 运行 程序时,我都得到了值来自初始化而不是来自函数的那个​​。如果有人能向我解释它是如何工作的,那将非常有帮助。

import UIKit

class ViewController: UIViewController {
    
    var number = Int()
    var points = 0
    
    @IBOutlet weak var calc: UILabel!
    @IBOutlet weak var button1: UIButton!                
    @IBOutlet weak var button2: UIButton!        
    
    @IBAction func add(_ sender: UIButton) {
        
        if sender.tag == number {
        print("Yes!")
            points += 1
            calc.text = String(points)
        }
        
        else {
            print ("no!")
            points -= 1
            calc.text = String(points)
            
        }
        add ()
    }
   

    override func viewDidLoad() {
         
        add ()
        
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }    
    
    func add () {
        
        var  number = Int.random(in: 0..<2)
        print(number)
        
        
        if number == 0 {
            
            button1.setTitle("click", for: .normal)
            button2.setTitle("don't click", for: .normal)             
            
        }
        
        else {
            button1.setTitle("don't click", for: .normal)
            button2.setTitle("click", for: .normal)
            
        }   
    }        
}

删除代码中 add() 内的 var

import UIKit

class ViewController: UIViewController {
    
    var number = Int()
    var points = 0
    
    @IBOutlet weak var calc: UILabel!
    @IBOutlet weak var button1: UIButton!                
    @IBOutlet weak var button2: UIButton!        
    
    @IBAction func add(_ sender: UIButton) {
        
        if sender.tag == number {
        print("Yes!")
            points += 1
            calc.text = String(points)
        }
        
        else {
            print ("no!")
            points -= 1
            calc.text = String(points)
            
        }
        add ()
    }
   

    override func viewDidLoad() {
         
        add ()
        
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }    
    
    func add () {
        
       // HERE
        self.number = Int.random(in: 0..<2)
        print(number)
        
        
        if number == 0 {
            
            button1.setTitle("click", for: .normal)
            button2.setTitle("don't click", for: .normal)             
            
        }
        
        else {
            button1.setTitle("don't click", for: .normal)
            button2.setTitle("click", for: .normal)
            
        }   
    }        
}