我想在 swift 中有一个函数,它需要两个参数,它们必须有一些基类并且每个参数都面对不同的协议(protocol)。
class func createContainerViewController<T:UIViewController, U:UIViewController>(withCenterViewController centerViewController: T, andLeftViewController leftViewController: U) -> ContainerViewController where T: CenterViewController, U: SidePanelViewController
但是每当我尝试使用这样的方法时:
let left: SidePanelViewController = UIStoryboard.leftViewController()!
let center: EventsListViewController = UIStoryboard.eventsListViewController()!
let containerViewController = ContainerViewController.createContainerViewController(withCenterViewController: center, andLeftViewController: left)
Xcode 给我一个错误
Generic parameter 'T' could not be inferred
变量 center 和 left 都是类的实例,它们继承自 UIViewController 并面对 T 或 U 所需的协议(protocol)。
createContainerViewController函数中的使用:
let container = ContainerViewController()
container.centerViewController = centerViewController
var centerViewController = container.centerViewController as! CenterViewController
centerViewController.delegate = container
container.leftViewController = leftViewController
var leftViewController = container.leftViewController as! SidePanelViewController
leftViewController.delegate = container
return container
这应该可行。
protocol CenterViewController {}
protocol SidePanelViewController {}
class Center: UIViewController, CenterViewController {}
class Left: UIViewController, SidePanelViewController {}
class ContainerViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let center = Center()
let left = Left()
let _ = ContainerViewController.createContainerViewController(withCenterViewController: center, andLeftViewController: left)
}
class func createContainerViewController<T:UIViewController, U:UIViewController>(withCenterViewController centerViewController: T, andLeftViewController leftViewController: U) -> ContainerViewController where T: CenterViewController, U: SidePanelViewController {
return ContainerViewController()
}
}
关于ios - Swift 中的多个泛型参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39635132/
欢迎光临 OStack程序员社区-中国程序员成长平台 (https://ostack.cn/) | Powered by Discuz! X3.4 |