![](/img/trans.png)
[英]Cannot convert value of type '(_) throws -> ()' to expected argument type '((UIAlertAction) -> Void)?'
[英]UIAlert Cannot convert value of type '(_) throws -> ()' to expected argument type '((UIAlertAction) -> Void)?'
我一直在尋找解決UIAlertAction
某些代碼的問題的解決方案。 我想將給定數字的SQLite數據庫中的值從true更新為false。 我設法使if / else循環正常工作,所以我知道我來對地方了。 但是,當我嘗試從UIAlertAction運行數據庫更新查詢時,出現上述錯誤。
代碼如下:
} else {
print ("Badge in School - check out")
let checkOut = UIAlertController(title: "Sign Out?", message: "Click on the 'Sign Out' button below to end your visit", preferredStyle: .alert)
let signOut = UIAlertAction(title: "Sign Out", style: .destructive) { (UIAlertAction) in
print ("Set Badge State to false")
let badgeOut = self.badgeTable.filter(self.badgeNumber == badgeNumberInt!)
let badgeOutUpdate = badgeOut.update(self.badgeIn <- false)
try self.myData.run(badgeOutUpdate)
}
let cancel = UIAlertAction(title: "Cancel", style: .cancel)
checkOut.addAction(signOut)
checkOut.addAction(cancel)
present (checkOut, animated: true, completion: nil)
}
如果我更改:
try self.myData.run(badgeOutUpdate)
至
try! self.myData.run(badgeOutUpdate)
該代碼將運行,並且完全符合我的期望。
我們將不勝感激地收到任何可以向像我這樣的白痴解釋的文件說明或指針!
您正在調用的run
方法可能會引發異常,但是警報操作關閉不會引發異常。 您必須處理異常,因為未設置警報操作以允許異常冒泡。 當您添加! 嘗試時,您說的是“執行此操作,如果發生異常,則使應用程序崩潰。” 另一種選擇是將其包裝在do-catch塊中:
do {
try self.myData.run(badgeOutUpdate)
} catch {
// Handle the exception here
}
如果遇到異常,它將執行catch塊。 如果不是這樣,則捕獲將被忽略。 另一種選擇是使用以下內容:
try? self.myData.run(badgeOutUpdate)
這將執行可能引發的呼叫。 如果該調用確實引發了異常,則它會靜默失敗並繼續執行您的程序。 在某些情況下這可能很好,或者可能意味着您的程序中沒有其他可用的方法。
每種情況都不同,請選擇最適合您的方法:發生異常崩潰,處理異常,靜默失敗。
Swift文檔很好地涵蓋了這一點: https : //docs.swift.org/swift-book/LanguageGuide/ErrorHandling.html
您需要do-catch
塊
do {
try self.myData.run(badgeOutUpdate)
}
catch {
print(error)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.