Home>
@IBAction func othersLocation (_ sender: Any)
{
   ref.child ("test"). observeSingleEvent (of: .value, with: {(snapshot) in
        let value = snapshot.value as? NSDictionary
        let a = value? ["userTest"] as? Double
        let b = value? ["userTest2"] as? Double
        print ("Location information has been acquired")
        })
        // Use of unresolved identifier 'a'
        if let c = a
        {
            Use of unresolved identifier 'b'
            if let d = b {
            // omitted
            }
        }
}


When I want to declare and use data newly obtained from the database as c, b in this way
Use of unresolved identifier 'c'
Use of unresolved identifier 'd'
How do I declare it?

  • Answer # 1

    Check the variable scope.
    Variables declared inside a function are local variables and cannot go out of the function.

    The simplest is to create a variable to hold the value in the ViewController that holdsothersLocation.

    var valueOfUserTest: Double?
    var valueOfUserTest2: Double?

    Specify an optional (?) and leave it nil until the end of reading, so that you can distinguish between before and after data acquisition.
    You cannot create a constant that will be valid once the data is acquired. I think it's a good idea to use the optional.

    I think the better way is to prepare a singleton "Model" and have it hold the value.