我有一个 Swift 函数,它使用 switch 语句来处理各种枚举情况,但我还需要同时检查另一个条件。我能想到的最佳解决方案是使用嵌套开关(有效),但我想知道是否有更优雅(Swifty?)的方式?
代码是不言自明的:
func transitionTo(scene: Scene, transition: SceneTransitionType) -> Observable<Void> {
let subject = PublishSubject<Void>()
let viewController = scene.viewController()
switch viewController {
case is UISplitViewController:
switch transition {
case .root:
window.rootViewController = viewController
subject.onCompleted()
default:
fatalError("UISplitViewController can only be exist at the root of the view hierachy")
}
default:
switch transition {
case .root:
window.rootViewController = viewController
subject.onCompleted()
case .push(let animated):
guard let nc = currentViewController as? UINavigationController else {
fatalError("Unab;e to push a view controlled without an existing navigation controller")
}
_ = nc.rx.delegate // one-off sub to be notified when push complete
.sentMessage(#selector(UINavigationControllerDelegate.navigationController(_:didShow:animated:)))
.map { _ in }
.bind(to: subject)
nc.pushViewController(viewController, animated: animated)
currentViewController = SceneCoordinator.topViewControllerInStackWith(root: viewController).first!
case .modal(let animated):
currentViewController.present(viewController, animated: animated) {
subject.onCompleted()
}
currentViewController = SceneCoordinator.topViewControllerInStackWith(root: viewController).first!
}
最佳答案
据我所知,这是使用单个 switch 语句的最佳方式。
func transitionTo(scene: Scene, transition: SceneTransitionType) -> Observable<Void> {
let subject = PublishSubject<Void>()
let viewController = scene.viewController()
switch transition {
case .root:
window.rootViewController = viewController
subject.onCompleted()
case .push(let animated):
if viewController is UISplitViewController {
fatalError("UISplitViewController can only be exist at the root of the view hierachy")
return
}
guard let nc = currentViewController as? UINavigationController else {
fatalError("Unab;e to push a view controlled without an existing navigation controller")
}
_ = nc.rx.delegate // one-off sub to be notified when push complete
.sentMessage(#selector(UINavigationControllerDelegate.navigationController(_:didShow:animated:)))
.map { _ in }
.bind(to: subject)
nc.pushViewController(viewController, animated: animated)
currentViewController = SceneCoordinator.topViewControllerInStackWith(root: viewController).first!
case .modal(let animated):
if viewController is UISplitViewController {
fatalError("UISplitViewController can only be exist at the root of the view hierachy")
return
}
currentViewController.present(viewController, animated: animated) {
subject.onCompleted()
}
currentViewController = SceneCoordinator.topViewControllerInStackWith(root: viewController).first!
}
}
关于swift - 检查 switch 语句中的多个条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51670632/