【发布时间】:2018-12-12 07:27:18
【问题描述】:
我有这个协议:
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)
}
我面临的问题是它显示以下警告
冗余约束 'Self' : 'AnyObject'
这是因为我同时使用了 class 和 where Self: UIViewController,但我两者都需要!原因在于我的协议扩展(见下文),我使用 UIViewController 方法,如果我删除 class,我的扩展会显示一个错误,要求添加 mutating,这它不应该有,因为它只是一个类协议。
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)
}
}
}
那么,有没有更好的解决方案?我可以删除警告吗?
【问题讨论】:
-
将方法声明为变异有什么问题?
-
问题是这个协议只适用于视图控制器&我使用一个var的didset中的一种方法,我收到一个错误,要求我使didset发生变异&在这样做之后它显示了另一个错误说变异只添加到函数中
-
那你能把
didSet中的代码显示出来吗? -
下载最新的工具链swift.org/download (Trunk Development (master)) 我觉得你不需要额外的约束
标签: ios swift uiviewcontroller