我正在构建 iOS 应用程序的状态恢复。我目前有
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
总是返回 Controller 。我正在尝试找到一个结构,在该结构中我不会拥有所有这些 if
。
我试过类似的东西:
let checks = [
"SetupPagesViewController": SetupPagesViewController.self,
"MainViewController": MainViewController.self,
]
if let clazz = checks[controllerIdentifier] where ctrl is clazz {
return ctrl
}
但是编译器不允许。我找不到一种方法来存储我的 class
类型以便在 if
中重用它。
这可能吗?如何?谢谢
最佳答案
您可以为此使用 Objective-C 运行时(由 Foundation 公开)的内省(introspection)工具,即 NSObject
的 isKindOfClass
方法:
let checks: [String:AnyClass] = [
"SetupPagesViewController": SetupPagesViewController.self,
"MainViewController": MainViewController.self,
]
if let clazz = checks[controllerIdentifier] where ctrl.isKindOfClass(clazz) {
return ctrl
}
请注意,要使其正常工作,类必须继承自 NSObject
。
关于ios - 在 Swift 2 中动态检查对象类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32274511/