I have been searching around but couldn't find a solution. can someone please let me know what I am doing wrong. here is my function code: in my database I have hour=5 as Int and Minute=45 as Int but when I print, the values of the function prints 0,0
我一直在寻找,但找不到解决方案。有人可以让我知道我做错了什么。这是我的功能代码:在我的数据库中我有小时= 5作为Int和Minute = 45作为Int但是当我打印时,函数的值打印0,0
var docRefF : DocumentReference!
func getTime()-> (Int, Int){
var FHour = Int()
var FMinute = Int()
docRefF = Firestore.firestore().document("sampleTime/worktime")
dataListener = docRefF.addSnapshotListener { (docSnapshot, error) in
guard let docSnapshot = docSnapshot, docSnapshot.exists else { return }
let data = docSnapshot.data()
let Hour:Int = data["Hour"]! as! Int
let Minute: Int = data["Minute"]! as! Int
FHour = Hour
FMinute = Minute
}
return (FHour, FMinute)
}
let time = getTime()
print("\(time.0),\(time.1)" )
//printed 0,0
1 个解决方案
#1
0
Clearly its issue of asynchronous execution. Use * function with Closure* Instead of function with returning value.
显然它是异步执行的问题。使用* function with Closure *而不是返回值的函数。
Please refer following code
请参考以下代码
var docRefF : DocumentReference!
func getTime(_ then:(_ first:Int, _ second:Int)->()){
var FHour = Int()
var FMinute = Int()
docRefF = Firestore.firestore().document("sampleTime/worktime")
dataListener = docRefF.addSnapshotListener { (docSnapshot, error) in
guard let docSnapshot = docSnapshot, docSnapshot.exists else { return }
let data = docSnapshot.data()
let Hour:Int = data["Hour"]! as! Int
let Minute: Int = data["Minute"]! as! Int
FHour = Hour
FMinute = Minute
//TODO:- Use other firebase related task same as your code, so that uncomment other lines same as your origional
then(FHour, FMinute) // This is closure call back line
}
}
//Calling your function
getTime { (first, second) in
print(first,second)
}
#1
0
Clearly its issue of asynchronous execution. Use * function with Closure* Instead of function with returning value.
显然它是异步执行的问题。使用* function with Closure *而不是返回值的函数。
Please refer following code
请参考以下代码
var docRefF : DocumentReference!
func getTime(_ then:(_ first:Int, _ second:Int)->()){
var FHour = Int()
var FMinute = Int()
docRefF = Firestore.firestore().document("sampleTime/worktime")
dataListener = docRefF.addSnapshotListener { (docSnapshot, error) in
guard let docSnapshot = docSnapshot, docSnapshot.exists else { return }
let data = docSnapshot.data()
let Hour:Int = data["Hour"]! as! Int
let Minute: Int = data["Minute"]! as! Int
FHour = Hour
FMinute = Minute
//TODO:- Use other firebase related task same as your code, so that uncomment other lines same as your origional
then(FHour, FMinute) // This is closure call back line
}
}
//Calling your function
getTime { (first, second) in
print(first,second)
}