いくつかの名前を配列にダウンロードする必要がありますが、ダウンロードする名前の数は正確にはわかりません。すべての名前がダウンロードされた後で、実行するカスタム関数が必要です。Swift Closure Expression
私はカスタム関数を呼び出すためにクロージャを使用しますが何が起こるかは、最初の名前をダウンロードしたら、私のカスタム関数は、それから2番目の名前がダウンロードされ、すぐに呼ばなっている、カスタム関数が
など再び呼ばれています名前をダウンロードした後ではなく、すべての名前が配列にダウンロードされた後に呼び出されるようにするには、カスタム関数が必要です。私はどこで何か間違っているのですか?
これは私が取得していますものです:これは私が欲しいものである
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()
}
}
}
。 'Bool'を直接使用してください。また、 'nameArray'のような名前を付けないでください。単にそれを '名前'と呼んでください。複数のことは、配列のようなコレクションであることを意味します。 – Alexander
@Alexander Momchliovアドバイスありがとう! –