Xcode 13报Redundant superclass constraint冗余约束错误如何解决
错误原因
你在定义HasWaitAnimation协议时已经明确指定它只能被UIViewController及其子类遵守:protocol HasWaitAnimation: UIViewController,这已经隐含了所有遵守该协议的类型必然是UIViewController的子类,所以扩展里额外添加的where Self: UIViewController约束完全冗余,Xcode 13及以上版本的Swift编译器会对这类冗余约束主动抛出编译错误。
解决方案
你可以根据自己的业务需求选择以下任意一种方案处理:
方案1:直接删除扩展的冗余约束(最优解)
把扩展声明行的where条件直接删掉即可,修改后可以正常编译,协议本身的限制已经可以保证扩展内可以正常调用UIViewController的所有原生方法(比如present):
extension HasWaitAnimation { func showAlertWait(message: String, completion: @escaping()->Void) { DispatchQueue.main.async { let activitiyViewController = ActivityViewController(message: message) self.present(activitiyViewController, animated: false, completion: { completion() }) self.alertWait = activitiyViewController } } func hideAlertWait (completion: @escaping () -> Void) { DispatchQueue.main.asyncAfter(deadline: .now()+0.2, execute: { self.alertWait?.dismiss(animated: true, completion: completion) self.alertWait = nil }) } }
方案2:修改协议定义,放开协议继承限制
如果你后续有让非UIViewController类型也遵守该协议的需求,可以把协议定义里的: UIViewController继承规则去掉,保留扩展的where约束即可:
protocol HasWaitAnimation { var alertWait: ActivityViewController? {get set} } extension HasWaitAnimation where Self: UIViewController { // 原有扩展实现保持不变 }
该方案下只有UIViewController及其子类的协议遵守者,才能获得两个动画方法的默认实现。
内容的提问来源于stack exchange,提问作者RFComp
相关产品推荐
相关产品推荐

