-1

I pass a parameter uid to my function checkIfUserExists and make an async call. However I am unable to access uid within the callback of the async call.

class Database {
    func checkIfUserExists(uid: String){
        let db = Firestore.firestore()
        db.collection("users").document(uid).getDocument { (snapshot, err) in
            if let document = snapshot, document.exists {
                print("User exists")
            } else {
                print("User does not exist, createUser()")
                createUser(uid: uid) 
            }
        }
    }
}

The error:

Call to method 'createUser' in closure requires explicit 'self.' to make capture semantics explicit

Any idea how I access uid or pass it to the async call so I can pass it to createUser()?

Zorgan
  • 8,227
  • 23
  • 106
  • 207
  • 2
    The issue is not uid, but `createUser`. Simply prepend `self.` to the `createUser` call and the compiler should be happy. You might however have to check wether you want to have a weak reference to self, as doing the above implies you want a strong reference. – Sander Saelmans Jun 16 '20 at 21:57
  • Thanks this was the issue – Zorgan Jun 17 '20 at 07:57

1 Answers1

1

The error is telling you createUser requires self since you're capturing the Database instance inside your closure.

self.createUser should solve your problem but you should consider if you need to add [weak self] in (snapshot, err) in to your closure to prevent a retain cycle.

Yariv Nissim
  • 13,273
  • 1
  • 38
  • 44