我有这个协议:
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)
}
我面临的问题是它显示以下警告:
这是因为我同时使用了class和where Self: UIViewController,但我需要两者!原因在于我的协议扩展(如下所示)中使用了UIViewController方法。如果我删除class,我的扩展将显示一个错误,要求添加mutating,但这不应该出现,因为它只是一个类协议。Redundant constraint 'Self' : 'AnyObject'
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)
}
}
}
那么,有更好的解决方案吗?我能消除这个警告吗?
didSet
中的代码吗? - Sweeper