'How do I filter view controller by type?
This is my simple function:
func popTo<T: UIViewController>(type: T.Type, from context: UINavigationController?) {
let mytype = type
guard let controller = context?.viewControllers.first(where: { $0 is T }) else {
return
}
print(mytype) //1
print(context?.viewControllers) //2
print(controller) //3
context?.popToViewController(controller, animated: true)
}
After I put a breakpoint and print out the following lines, I get console output:
PLZ.GroupViewController //1
▿ Optional<Array<UIViewController>> //2
▿ some : 5 elements
▿ 0 : <PLZ.GroupsViewController: 0x11dd68660>
▿ 1 : <PLZ.GroupViewController: 0x11f415c70>
▿ 2 : <PLZ.ProductViewController: 0x11f619d00>
▿ 3 : <PLZ.ConfirmViewController: 0x11f538cd0>
▿ 4 : <PLZ.ConfirmationViewController: 0x11f53e330>
<PLZ.GroupsViewController: 0x11dd68660> //3
Why it returns GroupsViewController when it should GroupViewController?
How do I call that function?
if let type = viewModel.returnControllerType {
print(type) //4
self?.router.popTo(type: type, from: self?.navigationController)
}
PLZ.GroupViewController //4
returnControllerType is defined:
let returnControllerType: UIViewController.Type?
Solution 1:[1]
The simplest solution ever is:
func popTo<T: UIViewController>(type: T.Type, from context: UINavigationController?) {
guard let controller = context?.viewControllers.first(where: { $0.isKind(of: type) }) else {
return
}
context?.popToViewController(controller, animated: true)
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Bartłomiej Semańczyk |
