Swift 4函数为多个返回值返回0 [英] Swift 4 function returning 0 for multiple return values
本文介绍了Swift 4函数为多个返回值返回0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我一直在搜索,但是找不到解决方案.有人可以让我知道我在做什么错.这是我的功能代码:在我的数据库中,我将hour = 5设为Int,将Minute = 45设为Int但是当我打印时,该函数的值打印0,0
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
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
推荐答案
很显然,它是异步执行的问题.将 *函数与Closure * 结合使用,而不要使用具有返回值的函数.
Clearly its issue of asynchronous execution. Use * function with Closure* Instead of function with returning value.
请参考以下代码
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)
}
这篇关于Swift 4函数为多个返回值返回0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文