我正在構建iOS應用程序的狀態恢復。我目前有動態檢查Swift 2中的對象類型
func application(application: UIApplication, viewControllerWithRestorationIdentifierPath identifierComponents: [AnyObject], coder: NSCoder) -> UIViewController? {
guard let controllerIdentifier = identifierComponents.last as? String else {
return nil
}
guard let ctrl = self.window?.rootViewController else {
return nil
}
if controllerIdentifier == "SetupPagesViewController" && ctrl is SetupPagesViewController {
return ctrl
} else if controllerIdentifier == "MainViewController" && ctrl is MainViewController {
return ctrl
}
return nil
}
在哪裏我發現最後一行有點難看。我可能會有更多的if
這將永遠返回控制器。我試圖找到一個構造,我不會擁有所有那些if
s。
我試圖用之類的東西:
let checks = [
"SetupPagesViewController": SetupPagesViewController.self,
"MainViewController": MainViewController.self,
]
if let clazz = checks[controllerIdentifier] where ctrl is clazz {
return ctrl
}
但是編譯器不會讓我。我無法找到存儲我的class
類型的方法,以便在if
中重複使用它。
這可能嗎?怎麼樣?由於