2017-06-22 66 views
0

我想讓用戶重置他/她的遊戲得分(基本let值最初爲0,但我在最後一次addAction時收到一個錯誤,告訴我: 無法將類型的價值 '() - >()' 到期望的參數類型 '((UIAlertAction) - >無效)?'@IBAction生成錯誤 - 無法執行代碼來重置Int值

請幫我這裏是代碼,我提到了塊:

@IBAction func resetScore() { 
    let alertController = UIAlertController(title: "Reset", message: "Are you sure you want to reset your game score? All progress will be lost.", preferredStyle: UIAlertControllerStyle.alert) 

    alertController.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.default, handler: nil)) 

    alertController.addAction(UIAlertAction(title: "Reset", style: UIAlertActionStyle.default, handler: { 
     func resetScore() { 
      let score = 0 
      scoreCounter.text = "Score: " + String(score) 
     } 
    })) 

    present(alertController, animated: true, completion: nil) 
} 

回答

0

這是因爲封閉期望一個參數,你需要在末尾寫_ in

alertController.addAction(UIAlertAction(title: "Reset", style: UIAlertActionStyle.default, handler: { _ in 

此外,如果你希望在按下按鈕時要調用的函數resetScore,那麼你就需要將代碼更新到以下幾點:

alertController.addAction(UIAlertAction(title: "Reset", style: UIAlertActionStyle.default, handler: { _ in 
    let score = 0 
    self.scoreCounter.text = "Score: " + String(score) 
})) 

而且,在此基礎上的核心你正在聲明一個新的局部變量let scope行,這意味着你沒有重置任何東西。我猜你有一個名爲scope一個實例變量,所以下面會做什麼:

self.score = 0 
self.scoreCounter.text = "Score: " + String(score) 
+0

如果我的回答你的問題是有幫助的,並履行,那麼請接受它作爲回答您的文章,表示對其他用戶說你的問題已經解決:) https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work – Kumuluzz