2016-12-07 1 views
1

잠시 동안이 함수가 반환하는 값을 viewDidLoad의 외부 변수에 할당하는 데 어려움을 겪고 있지만 빈 문자열을 반환합니다. getUid() - firebase의 uid를 반환합니다. prRef - 사용자를 위해 firebase 테이블을 호출합니다.Swift에서 문자열 함수 외부에 변수를 지정합니다. 3

누군가 내가 뭘 잘못하고 있다고 말할 수 있습니까? 사전에

감사합니다,

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 
} 

사용 :

currentWorkplaceId = getCurrentWorkplaceId() 
+0

그 동기의 혼합물 (getCurrentWorkpaceId()가 동기) 및 비동기 (observesingleevent가 비동기). 그렇게 섞어서는 안됩니다. 클로저가 workplaceid에 값을 할당하기 전에 return 문을 실행하기 때문에 * 작동하지 않습니다. observeSingleEvent가 getCurrentWorkplaceId – Gruntcakes

답변

1

observeSingleEvent는 콜백 아마 비동기입니다. 따라서 전화를 걸 때 workplaceid은 (는) 아직 지정되지 않았습니다. 자신의 콜백을 사용하여 동일한 작업을 수행해야합니다.

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) 
    }) 
} 

용도 :

getCurrentWorkplaceId() { workplaceId in 
    self.currentWorkplaceId = workplaceId 
} 
+0

에 값을 전달하는 것과 같은 방식으로 getCurrentWorkplaceId()를 변경하여 closure를 통해 호출자에게 workplaceid의 값을 전달하십시오. 고마워 Frankie! 그것은 매력처럼 작동했습니다. – Rob