2016-04-16 30 views
0

我試圖創造一個迅速擴展情節串連圖板,以更安全的實例化視圖控制器UIStoryboard擴展

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" 
    } 
} 

發生編譯時錯誤。 「‘標識符’是ambituous在這個上下文類型查找」

回答

1

你可以這樣說:

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) 
    } 
} 

你可以在迅速herehere.

消除了與枚舉硬編碼字符串的討論
+0

謝謝你的回答。這非常簡單。它可以適用於我的情況。我創建了一個Identifier協議,因爲我在UIImage和UIViewControllers中實現了它作爲segueIdentifier。 –