2016-11-16 70 views
0

我必須將一些名稱下載到數組中,但我不確切知道將會下載多少個名稱。只有在下載完所有名稱後,我需要一個自定義函數才能運行。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() 
     } 
    } 
} 
+0

沒有必要爲'== TRUE;檢查了'Bool'。只需直接使用'Bool'即可。另外,避免命名諸如'nameArray'之類的東西。把它叫做'名字'。多數意味着它是一個像數組一樣的集合。 – Alexander

+0

@Alexander Momchliov感謝您的建議! –

回答

1

addAllNamesToArrayThenRunClosure實際上只添加了一個名稱,並且每個名稱都調用一次。如果你在那裏打電話給你的完成處理程序,它將被稱爲...每個名稱一次。您需要重新設計,以便在添加所有名稱後調用閉包。

這是我會怎麼做:

//There actually can be 1 or 100 names but I just used 3 for the example 
var randomNames = ["Mable", "Marlene", "Moses"] 
var globalNames = [String]() 

func add(names: [String], completionHandler: (_ success: Bool) -> Void) { 
    globalNames.append(contentsOf: names) 

    completionHandler(true) 
} 

add(names: randomNames) { success in 
    if success { 
     print("Finished") 
    } 
} 
+0

我想你已經在想這個了。通過你所描述的,你不需要一個完成處理程序,或者任何這個。 「隨機名稱」的來源是什麼? – Alexander

+0

那麼,爲什麼不只是一個數組? – Alexander

+0

'globalNames + = photos.flatMap {$ 0.metadata?.dowbloadUrl()?. absoluteString}' – Alexander

1

我建議增加for循環中addAllNamesToArrayThenRunClosure方法。然後,可以在添加完所有名稱後調用完成處理程序。

var randomNames = ["Mable", "Marlene", "Moses"] 
var nameArray = [String]() 

func addAllNamesToArrayThenRunClosure(completionHandler: (success: Bool) ->()) { 
    for name in randomNames { 
     nameArray.append(name) 
    } 
    completionHandler(true) 
} 

然後,調用從完成處理您的自定義功能,像這樣:

addAllNamesToArrayThenRunClosure() { success in 
    self.customFunction() 
}