如何在当前类型的Swift中使用泛型函数

时间:2018-07-31 07:57:30

标签: swift generics protocols

我有一个带有通用函数的协议,该协议返回通用ViewController。迫使我在默认实现中添加类型约束检查。

protocol RouterViewController {
    func getViewController<T: UIViewController>(_ name: Storyboard) -> T
}

extension RouterViewController {
    func getViewController<T>(_ name: Storyboard) -> T where T: UIViewController {
        let storyBoard = UIStoryboard.init(storyboard: name)
        return storyBoard.instantiateViewController()
    }
}

在没有泛型的情况下我可以做的同一示例

    struct RouterViewController {
     static func  getViewController(_ name: Storyboard) -> UIViewController {
     let storyBoard = UIStoryboard.init(storyboard: name)
            return storyBoard.instantiateViewController()
 }
}

我有一系列问题

  1. 如果我必须进行类型检查,那么我将使用工厂方法吗?如何使用泛型?
  2. 如果我想使用泛型方法如何在此函数中检查当前类型,请返回func<SignIn>() -> T

1 个答案:

答案 0 :(得分:0)

如果您在协议声明/扩展中进行小的更改,您将获得所需的功能:

protocol RouterViewController {
    func getViewController<T: UIViewController>(_ viewControllerType: T.Type, _ name: Storyboard) -> T 
}

extension RouterViewController {
    func getViewController<T>(_ viewControllerType: T.Type, _ name: Storyboard) -> T where T: UIViewController {
        let storyBoard = UIStoryboard.init(storyboard: name)
        let identifier = String(describing: T.self) // Let's say view controller's storyboard identifier is same as class name
        return storyBoard.instantiateViewController(withIdentifier: identifier) as! T
    }
}

用法:

struct TestStruct: RouterViewController {

}

TestStruct().getViewController(TestViewController.self, #YourStoryboardObject)

有关视图控制器和情节提要的更多信息,请检查:Swift protocol extension