我必須將一些名稱下載到數組中,但我不確切知道將會下載多少個名稱。只有在下載完所有名稱後,我需要一個自定義函數才能運行。Swift Closure表達式
我用封閉來調用自定義函數,但發生的事情是,一旦名字被下載,我的自定義功能是越來越立即調用,那麼第二個名字被下載,然後將自定義函數被再次叫等
我需要自定義函數才能在所有名稱下載到數組後才被調用,而不是在每個名稱被下載後。我在哪裏做錯了什麼?
這就是我得到:
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'之類的東西。把它叫做'名字'。多數意味着它是一個像數組一樣的集合。 – Alexander
@Alexander Momchliov感謝您的建議! –