2016-01-10 25 views
3

我有這個函數來呈現登錄/註冊模態視圖控制器。傳遞的參數必須是UIViewController<AuthViewControllerDelegate>UIViewController用於呈現方法,AuthViewControllerDelegate用於委託方法)swift如何傳遞UIViewController類型的參數<XXXDelegate>

static func checkAuthError(controller: UIViewController<AuthViewControllerDelegate>, err: NSError) { 
    if err.code == 401 { 
     let authViewController = viewControllerWithIdentifier("AuthViewController") as! AuthViewController 
     authViewController.delegate = controller 
     controller.presentViewController(authViewController, animated: true, completion: nil) 
    } 
} 

但我無法通過目標C風格類型。我是否必須通過同一個控制器兩次,使用不同的類型?

回答

2

您可以選擇任一類或協議類型的方法參數,並有條件地將它轉換爲另:

func checkAuthError(controller: UIViewController, err: NSError) { 
    ... 
    if authDelegate = controller as? AuthViewControllerDelegate { 
     ... 
    } 
} 

或者,你可以使用一個通用的類型約束:

func checkAuthError<T: UIViewController where T: AuthViewControllerDelegate>(controller: T, err: NSError) { 
    ... 
} 
0

它聽起來像

func checkAuthError<T: UIViewController where T: AuthViewControllerDelegate>(controller: T, err: NSError) { 
    ... 
} 

將很快被棄用,替換爲:

func checkAuthError<T: UIViewController>(controller: T, err: NSError) where T: AuthViewControllerDelegate { 
    ... 
} 

爲了清晰起見,where子句出現在任何返回值之後。

相關問題