Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
586 views
in Technique[技术] by (71.8m points)

xcode - Redundant conformance error message Swift 2

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?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You'll get that error message in Xcode 7 (Swift 2) if a subclass declares conformance to 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 declaration solves the problem:

class Subclass : MyClass {
    override var description: String { return "Subclass" }
}

But the superclass must declare the conformance explicitly, it is not automatically inferred from the existence of the description property.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...