1

I am struggling for a while to assign the value returned by this function to a variable outside of it, in viewDidLoad but is returning an empty string. getUid() - is returning the firebase uid prRef - is calling the firebase table for users

Can someone tell me what am I doing wrong?

Thanks in advance,

var currentWorkplaceId: String?

func getCurrentWorkplaceId() -> String {

    //completion:@escaping (Bool)->Void
    var workplaceid = String()
    prRef.child(getUid())
        .child("workplace_id")
        .observeSingleEvent(of: .value, with: { snapshot in
            workplaceid = snapshot.value as! String
    })
    return workplaceid
}

usage:

currentWorkplaceId = getCurrentWorkplaceId()
1
  • Its a mixture of synchronous (getCurrentWorkpaceId() is synchronous) and asynchronous, (observesingleevent is asynchronous). You can't mix them up like that. It is not working because the return statement is being executed before the closure is assigning the value to workplaceid. Change getCurrentWorkplaceId() to pass the value of workplaceid to the caller via a closure, in the same way observeSingleEvent is passing its value to getCurrentWorkplaceId Commented Dec 7, 2016 at 16:58

1 Answer 1

1

observeSingleEvent is probably asynchronous with a callback. So at the time you call return, workplaceid hasn't been assigned yet. You need to do the same with your own callback.

func getCurrentWorkplaceId(_ completion: @escaping (_ workplaceId: String)->()) {

    //completion:@escaping (Bool)->Void
    prRef.child(getUid())
    .child("workplace_id")
    .observeSingleEvent(of: .value, with: { snapshot in
        completion(snapshot.value as! String)
    })
}

Usage:

getCurrentWorkplaceId() { workplaceId in
    self.currentWorkplaceId = workplaceId
}
Sign up to request clarification or add additional context in comments.

1 Comment

Understood. Thanks a lot Frankie! It worked like a charm.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.