Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redundant constraint 'Self' : 'AnyObject'

I have this protocol:

protocol Container: class where Self: UIViewController {
    var containerView: UIView! { get }
    var currentChild: UIViewController? { get set }
    func remove(child viewController: UIViewController)
    func add(child viewController: UIViewController)
    func replaceCurrentViewController(with newChild: UIViewController)
}

the problem I am facing is that it shows the following warning

Redundant constraint 'Self' : 'AnyObject'

this is because I am using both class & where Self: UIViewController, but I need both! the reason for that is in my protocol extension (found below), I use UIViewController methods, and if I delete class, my extension shows an error asking for adding mutating, which it should not have because its a class only protocol.

extension Container {
    func remove(child viewController: UIViewController) {
        viewController.beginAppearanceTransition(false, animated: true)
        viewController.willMove(toParent: nil)
        viewController.removeFromParent()
        viewController.view.removeFromSuperview()
        viewController.endAppearanceTransition()
        currentChild = nil
    }

    func add(child viewController: UIViewController) {
        viewController.beginAppearanceTransition(true, animated: true)
        addChild(viewController)
        viewController.didMove(toParent: self)
        containerView.addSubview(viewController.view)
        viewController.view.frame = containerView.frame
        viewController.endAppearanceTransition()
        currentChild = viewController
    }

    func replaceCurrentViewController(with newChild: UIViewController) {
        if viewIfLoaded != nil, let currentChild = currentChild {
            if let parent = currentChild.parent, parent == self {
                remove(child: currentChild)
            }
            add(child: newChild)
        }
    }
}

so, is there a better solution? can I remove the warning?

like image 338
naif Avatar asked Dec 12 '18 07:12

naif


1 Answers

In swift 4 you can use

protocol Container where Self: UIViewController {
    var containerView: UIView! { get }
    var currentChild: UIViewController? { get set }
    func remove(child viewController: UIViewController)
    func add(child viewController: UIViewController)
    func replaceCurrentViewController(with newChild: UIViewController)
}

In swift 5 you can use

protocol Container: UIViewController {
    var containerView: UIView! { get }
    var currentChild: UIViewController? { get set }
    func remove(child viewController: UIViewController)
    func add(child viewController: UIViewController)
    func replaceCurrentViewController(with newChild: UIViewController)
}
like image 139
Irina Avatar answered Sep 28 '22 10:09

Irina