[英]swift how to pass parameter of type UIViewController<XXXDelegate>
I have this function to present signin/signup modal view controller. 我有这个功能来呈现登录/注册模态视图控制器。 The parameter passed has to be
UIViewController<AuthViewControllerDelegate>
( UIViewController
for presenting method, AuthViewControllerDelegate
for delegate method) 传递的参数必须是
UIViewController<AuthViewControllerDelegate>
(用于呈现方法的UIViewController
,用于委托方法的AuthViewControllerDelegate
)
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)
}
}
But I can't pass the objective c style type. 但我不能通过目标c样式类型。 Do I have to pass the same controller twice, with different types?
我是否必须使用不同类型的同一个控制器两次?
You could choose either the class or protocol type for the method argument and conditionally cast it to the other: 您可以为方法参数选择类或协议类型,并有条件地将其转换为另一个:
func checkAuthError(controller: UIViewController, err: NSError) {
...
if authDelegate = controller as? AuthViewControllerDelegate {
...
}
}
Alternatively, you could use a generic type constraint: 或者,您可以使用泛型类型约束:
func checkAuthError<T: UIViewController where T: AuthViewControllerDelegate>(controller: T, err: NSError) {
...
}
It sounds like 这听起来像
func checkAuthError<T: UIViewController where T: AuthViewControllerDelegate>(controller: T, err: NSError) {
...
}
will be deprecated soon, replaced by: 将很快弃用,取而代之的是:
func checkAuthError<T: UIViewController>(controller: T, err: NSError) where T: AuthViewControllerDelegate {
...
}
For clarity, the where
clause comes after any return values. 为清楚起见,
where
子句位于任何返回值之后。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.