2016-06-25 85 views
0

我已經斯威夫特文檔中被搜索和谷歌搜索,但無法找到如何從這樣的塊返回值:從封閉返回布爾

func checkIfplayerFellDown() -> Bool { 
    self.enumerateChildNodesWithName("brick", usingBlock: { 
     (node: SKNode!, stop: UnsafeMutablePointer <ObjCBool>) -> Bool in 
     if (node.position.y < self.player.position.y) { return false } 
    }) 
    return true 
} 

的問題是,因爲我不明白塊。我通常像這樣使用它們:

world.enumerateChildNodesWithName("name") {node, stop in 
     if (node.position.y < self.size.height*0.5) { 
      node.removeFromParent() 
     } 
    } 

如何從任何這些閉包中返回布爾值?我知道我應該在某個地方使用某種語法,我嘗試了一些東西,但沒有一個能夠工作,因爲我不知道這些模塊是如何工作的。

任何解釋或如何完成這個例子表示讚賞。

+0

她的第一個代碼塊將不起作用,因爲塊內的「返回false」從塊返回,但不會使'enumerateChildNodesWithName'完全返回,也不會使'checkIfplayerFellDown'函數返回false。實際上,它會導致編譯時錯誤,因爲塊必須返回void,而不是布爾值。 –

回答

2

使用局部變量(塊外,但裏面的方法)將結果傳遞出塊,並設置stoptrue當你想停止迭代:

func playerFellDown() -> Bool { 
    var result = true 
    self.enumerateChildNodesWithName("brick") { (child, stopOut) in 
     if child.position.y < self.player.position.y { 
      result = false 
      stopOut.memory = true 
     } 
    } 
    return result 
}