为了更安全地实例化视图控制器,我正在尝试创建一个快速的故事板扩展
protocol IdentifierType {
typealias Identifier: RawRepresentable
}
extension IdentifierType where Self: UIStoryboard, Identifier.RawValue == String {
func instantiateViewControllerWithIdentifier(identifier:Identifier) -> UIViewController {
return self.instantiateViewControllerWithIdentifier(identifier.rawValue)
}
}而且它不会在编译时出错。但是,当我试图实现它时,应该这样:
extension UIStoryboard : IdentifierType {
enum Identifier: String {
case MainViewController = "MAIN_VIEW_CONTROLLER"
case ContactUsViewController = "CONTACT_US_VIEW_CONTROLLER"
case AboutViewController = "ABOUT_VIEW_CONTROLLER"
}
}出现编译时错误。“在此上下文中,”标识符“对于类型查找是不稳定的”
发布于 2016-04-16 20:17:30
你可以这样说:
protocol IdentifierType {
associatedtype Identifier: RawRepresentable
}
extension UIStoryboard : IdentifierType {
enum Identifier: String {
case MainViewController = "MAIN_VIEW_CONTROLLER"
case ContactUsViewController = "CONTACT_US_VIEW_CONTROLLER"
case AboutViewController = "ABOUT_VIEW_CONTROLLER"
}
func instantiateViewControllerWithIdentifier(identifier:Identifier) -> UIViewController {
return self.instantiateViewControllerWithIdentifier(identifier.rawValue)
}
}然后,您可以调用类似于self.storyboard?.instantiateViewControllerWithIdentifier(.ContactUsViewController)的东西,这正是您想要的。
不确定在这种情况下拥有RawRepresentable的好处是什么,也许您可以解释为什么您认为需要使用它。
但假设这是您所需要的一切,协议IdentifierType是完全不必要的,因此可以简化为:
extension UIStoryboard {
enum Identifier: String {
case MainViewController = "MAIN_VIEW_CONTROLLER"
case ContactUsViewController = "CONTACT_US_VIEW_CONTROLLER"
case AboutViewController = "ABOUT_VIEW_CONTROLLER"
}
func instantiateViewControllerWithIdentifier(identifier:Identifier) -> UIViewController {
return self.instantiateViewControllerWithIdentifier(identifier.rawValue)
}
}https://stackoverflow.com/questions/36664870
复制相似问题