-7

i have variable in viewDidLoad(), so i can't make a new variable outside by variable in viewDidLoad(). May you help me please?

override func viewDidLoad() {
    super.viewDidLoad()

    ref = Database.database().reference()

    ref?.child("user_clicks").child(userID).observeSingleEvent(of: .value, with: { (snapshot) in

        if let snapDict = snapshot.value as? Dictionary <String, AnyObject>{

        let user_counts = snapDict["Counts"] as! Int

        print(user_counts)

        self.label_usercounts.text = String(user_counts)

        }

    }) { (error) in
        print(error.localizedDescription)
    }

}

var counts = user_counts

2 Answers2

0

viewDidLoad is a method, everything you declare inside a method can not be used outside of it.

When you declare a variable inside the curly braces of a method, this variable gets destroyed after the closing brace (except for static variables).

You need to read about variables scopes in Swift, read the documentation about that.

UPDATE: What you need to achieve according to your comments is to count how many times a method have been called, which can be achieved using static variables.

Unfortunately, Swift does not support static variables, but you can still do that like this:

func functionWithCounter() {
    struct Counter { static var numberOfCalls = 0 }

    Counter.numberOfCalls += 1 // numberOfCalls is the number of times the method functionWithCounter() has been called.
}

If you are reading the value of number of clicks from a database, then just read it from there, it should always have the most recent number of clicks, you shouldn't be counting them inside the method.

Mo Abdul-Hameed
  • 6,030
  • 2
  • 23
  • 36
-1

You can create a local and global variables. Global variables can access from anywhere inside the class, even if you create instance of class you can access them. However you're creating local variables inside the method which you can't access from outside the method .

The solution to your answer is create the variable outside the viewDidload() method and access that variable inside of the method and you can assign the value .

print statement is inside of the closure so you can use a self property of the variable and you can assign the value, later you can reuse the variable and it's value from anywhere.

Tushar Katyal
  • 412
  • 5
  • 12