2016-09-12 3 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) 
} 

전무 기본적으로는 그래서 나는 유형의 값을 변환 할 수 없습니다, 해당 매개 변수는 선택 사양 일 할 수 '() -> Void?'를 입력하십시오. 롭에

편집

덕분에, 지금은 구문 실행하지만 난 그것을 호출하려고 할 때 내가 얻을 :

유형의 값을 변환 할 수 없습니다 '()'예상 인수 유형 '(() - > 공허)? ' 나는 당신이 잘못된 위치에 물음표를 배치

showAlert(self, title: "Time", message: "10 Seconds", action: test()) 

test() { 
    print("Hello") 

}

+0

. '?'가 잘못된 위치에 있습니다. '(() -> Void)이어야합니까? = nil' – Rob

+0

그냥 내 질문을 편집했습니다. 네 권리가 있니? 떨어져서. 하지만 이제는 올바르게 호출하는 데 문제가 있습니다. – gradedcatfood

+0

편집을 다시하시오. showAlert (self, title : "Time", 메시지 : "10 Seconds", action : {print ("Hello")})'. 또는'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) 
{ 
    ... 
} 

을 그리고 당신이 그것을 호출 할 때 괄호를 포함하지 않는 :이 작동 당신이 선택하지 않으면, 당신이`nil` 할 수 없습니다

showAlert(self, title: "Time", message: "10 Seconds", action: test) 
+0

감사합니다! 함수 호출 후에()가 문제가되었습니다! – gradedcatfood

+0

'test()'는 "'test' 함수를 실행한다는 것을 의미합니다. 'test'만이''test'라는 함수를 가리 킵니다. –