2016-09-12 13 views
1

私は迅速にアラートビューを表示するラッパー関数を作成しています。ここで 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") 

}

+0

あなたはそれをオプションにしていない場合、あなたはそれ 'nil'することはできません。 '? 'は間違った場所にあります。 '(() - > Void)でなければなりません。 = nil' – Rob

+0

ただ私の質問を編集しました。あなたの権利はありましたか?オフ。しかし、今正しくそれを呼び出す問題がある – gradedcatfood

+0

あなたの編集、それは 'showAlert(自己、タイトル:"時間 "、メッセージ:" 10秒 "、アクション:{印刷("こんにちは)}) 'です。または 'showAlert(self、title:" Time "、メッセージ:" 10 Seconds "){print(" Hello ")}'。 – Rob

答えて

2

それを呼んでいる方法です。これは動作します:

// 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) 
+0

ありがとう!関数呼び出しの後の()は問題でした! – gradedcatfood

+0

'test()'は "関数' test'を実行することを意味します。 'test'だけでは' 'test'という関数 –

関連する問題