Home > Software engineering >  Problem in comparison with Array with type Coordinator swift
Problem in comparison with Array with type Coordinator swift

Time:07-10

I have a function called "childDidFinish" that receive a childCoordinator with type Coordinator, but when I try to compare the parameter received and the element Coordinator inside the Array the error is.

"Argument type 'Coordinator' expected to be an instance of a class or class-constrained type"

This is my Swift code, Thanks for your help

 private(set) var childCoordinators: [Coordinator] = []

private let navigationController: UINavigationController

init(navigationController: UINavigationController){
    self.navigationController = navigationController
}
func start() {
    let eventListViewController: EventListViewController = .instantiate()
    let eventListViewModel = EventListViewModel()
    
    eventListViewModel.coordinator = self
    eventListViewController.viewModel = eventListViewModel
    navigationController.setViewControllers([eventListViewController], animated: false)
}

func startAddEvent(){
    let addEventCoordinator = AddEventCoordinator(navigationController:navigationController)
    childCoordinators.append(addEventCoordinator)
    addEventCoordinator.start()
}

func childDidFinish(_ childCoordinator: Coordinator){
    
    if let index = childCoordinators.firstIndex(where: { coordinator -> Bool in
        return  childCoordinator === coordinator//There is the problem
    }){
        childCoordinators.remove(at: index)
    }
}

CodePudding user response:

I think your Coordinator is a protocol. But in order to be comparable with === it must be a class-only protocol, which means it should inherit from AnyObject (in recent version of Swift; in earlier Swift versions it had to inherit from class)

So all you need to do is add : AnyObject to a definition of your protocol:

protocol Coordinator: AnyObject {
   // ...
}

If this is not the case, then like @matt we need to see your Coordinator.

CodePudding user response:

You can alternatively make Coordinator Equatable, whichever it is (protocol, class or struct) and just use == instead of ===

  • Related