问题描述
我将我的项目更新到 Swift 2,并收到了一堆 XXX 与 YYY 协议的冗余一致性
.当类符合 CustomStringConvertible
时,这种情况尤其经常(或总是)发生.还有一些带有 Equatable
的地方.
class GraphFeatureNumbersetRange: GraphFeature, CustomStringConvertible {//<--- 在此处获取错误...}
我怀疑在实现 var description: String { get }
或协议要求的任何方法时,我不需要明确遵守协议.我应该按照 fixit 说明删除所有这些吗?如果一个类实现了协议的所有方法,Swift 现在会自动推断一致性吗?
如果子类声明一致性,您将在 Xcode 7 (Swift 2) 中收到该错误消息到一个已经从超类继承的协议.示例:
class MyClass : CustomStringConvertible {变量描述:字符串{返回MyClass"}}类子类:MyClass,CustomStringConvertible {覆盖变量描述:字符串{返回子类"}}
错误日志显示:
main.swift:10:27: 错误:子类"与协议CustomStringConvertible"的冗余一致性类子类:MyClass,CustomStringConvertible {^main.swift:10:7: 注意:子类"从这里的超类继承了对协议CustomStringConvertible"的一致性类子类:MyClass,CustomStringConvertible {^从子类声明中删除协议一致性解决问题:
class 子类:MyClass {覆盖变量描述:字符串{返回子类"}}
但是超类必须显式声明一致性,它是不会从 description
的存在自动推断财产.
I updated my project to Swift 2, and received a bunch of redundant conformance of XXX to protocol YYY
. This happens especially often (or always) when a class conforms to CustomStringConvertible
. Also some place with Equatable
.
class GraphFeatureNumbersetRange: GraphFeature, CustomStringConvertible { // <--- get the error here
...
}
I suspect that I don't need to explicitly conform to a protocol when I implement var description: String { get }
, or whatever methods the protocol requires. Should I just follow fixit instructions and remove all these? Does Swift now automatically infer the conformance if a class implements all the protocol's methods?
You'll get that error message in Xcode 7 (Swift 2) if a subclass declares conformanceto a protocol which is already inherited from a superclass. Example:
class MyClass : CustomStringConvertible {
var description: String { return "MyClass" }
}
class Subclass : MyClass, CustomStringConvertible {
override var description: String { return "Subclass" }
}
The error log shows:
main.swift:10:27: error: redundant conformance of 'Subclass' to protocol 'CustomStringConvertible' class Subclass : MyClass, CustomStringConvertible { ^ main.swift:10:7: note: 'Subclass' inherits conformance to protocol 'CustomStringConvertible' from superclass here class Subclass : MyClass, CustomStringConvertible { ^
Removing the protocol conformance from the subclass declarationsolves the problem:
class Subclass : MyClass {
override var description: String { return "Subclass" }
}
But the superclass must declare the conformance explicitly, it isnot automatically inferred from the existence of the description
property.
这篇关于冗余一致性错误消息 Swift 2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!