0
var username: String? = nil
self.ref.child("users").observeSingleEvent(of: .value, with: { (snapshot) in
    let usersProfile = snapshot.value as? NSDictionary
    let userProfile = usersProfile![userID] as? NSDictionary
    username = userProfile!["username"] as! String

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

Why is the variable username not updated in the end?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Ricky Geng
  • 177
  • 1
  • 2
  • 10
  • Try this link [https://stackoverflow.com/questions/33367183/swift-read-data-from-nsdictionary](https://stackoverflow.com/questions/33367183/swift-read-data-from-nsdictionary) –  Dec 08 '18 at 05:51
  • 1
    Do some searching on the meaning of "asynchronous". You are printing `username` long before it is set. – rmaddy Dec 08 '18 at 15:34

1 Answers1

-1

You can try like this

  var username: String? = nil

    self.ref.child("users").observeSingleEvent(of: .value, with: { (snapshot) in

       if let usersProfile = snapshot.value as? NSDictionary, let userProfile = usersProfile![userID] as? NSDictionary, let name = userProfile!["username"] as? String {
username = name
}

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

    print(username)
Kathiresan Murugan
  • 2,783
  • 3
  • 23
  • 44