私は迅速にアラートビューを表示するラッパー関数を作成しています。ここで Swift関数パラメータデフォルト値
は、現在作業中のコードですが、現在、私はそれが可能な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)
}
が、私は関数を渡すことができるようにしたい.presentViewController機能で「完了」パラメータに関数を渡す必要はありませんshowAlertにその機能を持っているが期待引数に「)(」完了の下と呼ばれるが、私は次のことを得る
// 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)
}
nilをデフォルトでそれがあるので、私は型の値を変換することはできません、そのパラメータはオプションになりたいこと'() - > Void?'と入力します。 - 期待される引数の型「(()に「)(」
は、型の値を変換することはできません。
EDITロブへ
おかげで、今では構文的に実行されますが、私はそれを呼び出すようにしようとすると、私が取得します>ボイド)? 'ここで
は、私はあなたが間違った場所に疑問符を置い
showAlert(self, title: "Time", message: "10 Seconds", action: test())
test() {
print("Hello")
}
あなたはそれをオプションにしていない場合、あなたはそれ 'nil'することはできません。 '? 'は間違った場所にあります。 '(() - > Void)でなければなりません。 = nil' – Rob
ただ私の質問を編集しました。あなたの権利はありましたか?オフ。しかし、今正しくそれを呼び出す問題がある – gradedcatfood
あなたの編集、それは 'showAlert(自己、タイトル:"時間 "、メッセージ:" 10秒 "、アクション:{印刷("こんにちは)}) 'です。または 'showAlert(self、title:" Time "、メッセージ:" 10 Seconds "){print(" Hello ")}'。 – Rob