【发布时间】:2017-03-31 04:21:39
【问题描述】:
我必须将一些名称下载到一个数组中,但我不知道将下载多少个名称。只有在下载完所有名称后,我才需要运行自定义函数。
我使用闭包来调用自定义函数,但是一旦下载了第一个名称,我的自定义函数会立即被调用,然后下载第二个名称,然后再次调用自定义函数等等。
我需要仅在将所有名称下载到数组后调用自定义函数,而不是在下载每个名称后调用。我在哪里做错了什么?
这就是我得到的:
Mable
This should only print once not three times
Marlene
This should only print once not three times
Moses
This should only print once not three times
这就是我想要的:
Mable
Marlene
Moses
This should only print once not three times
如果可能,我希望在内部解决问题:addAllNamesToArrayThenRunClosure
代码:
//There actually can be 1 or 100 names but I just used 3 for the example
var randomNames = ["Mable", "Marlene", "Moses"]
var nameArray = [String]()
func addAllNamesToArrayThenRunClosure(name: String, completionHandler: (success:Bool)->()){
nameArray.append(name)
print(name)
let flag = true
completionHandler(success:flag)
}
func customFunction(){
print("This should only print once not three times")
}
for name in randomNames{
addAllNamesToArrayThenRunClosure(name){
//Shouldn't this run only after the array is filled?
(success) in
if success == true{
customFunction()
}
}
}
【问题讨论】:
-
== true无需检查Bool。只需直接使用Bool。另外,避免命名nameArray之类的东西。就叫它names。复数意味着它是一个像数组一样的集合。 -
@Alexander Momchliov 感谢您的建议!
标签: arrays swift callback closures