![](/img/trans.png)
[英]Swift: Default function parameter value via NotificationCenter
[英]Swift Function Parameter Default Value
我正在創建一個包裝器功能,以快速呈現警報視圖。
這是當前的工作代碼,但是目前我無法在.presentViewController函數中為“ completion”參數傳遞函數
func showAlert(viewClass: UIViewController, title: String, message: String)
{
// Just making things easy to read
let alertController = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction(UIAlertAction(title: "Okay", style: UIAlertActionStyle.Default, handler: nil))
// Notice the nil being passed to "completion", this is what I want to change
viewClass.presentViewController(alertController, animated: true, completion: nil)
}
我希望能夠將一個函數傳遞給showAlert並在完成時調用該函數,但是我希望該參數是可選的,因此默認情況下為nil
// Not working, but this is the idea
func showAlert(viewClass: UIViewController, title: String, message: String, action: (() -> Void?) = nil)
{
let alertController = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction(UIAlertAction(title: "Okay", style: UIAlertActionStyle.Default, handler: nil))
viewClass.presentViewController(alertController, animated: true, completion: action)
}
我得到以下信息,無法將類型'()'的值轉換為預期的參數類型'()->空嗎?'
編輯
感謝Rob,它現在可以在語法上運行,但是當我嘗試調用它時,我得到:
無法將類型'()'的值轉換為預期的參數類型'(()-> Void)?
這是我的稱呼方式
showAlert(self, title: "Time", message: "10 Seconds", action: test())
test() {
print("Hello")
}
您將問號放在錯誤的位置。 這有效:
// wrong: action: (() -> Void?) = nil
// right: action: (() -> Void)? = nil
func showAlert(viewClass: UIViewController, title: String, message: String, action: (() -> Void)? = nil)
{
...
}
並且在調用時不要包括方括號:
showAlert(self, title: "Time", message: "10 Seconds", action: test)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.