Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redundant conformance error message Swift 2

Tags:

xcode

swift

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?

like image 743
Khanh Nguyen Avatar asked Jun 16 '15 12:06

Khanh Nguyen


3 Answers

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.

like image 122
Martin R Avatar answered Oct 16 '22 02:10

Martin R


For googlers, I also got this error when including SwiftyJson in my Tests target and adding a swift test class, as it caused SwiftyJson to be compiled in again, and it declares NSNumber as Comparable. The solution was to only include it in the app target.

like image 37
Christopher Pickslay Avatar answered Oct 16 '22 00:10

Christopher Pickslay


The point is that your GraphFeatureNumbersetRange is NSObject's subclass. Which in its turn already conforms to CustomStringConvertible! That's it! Just delete this redundant protocol. Now you're declaring it twice! :-)

like image 2
Vitya Shurapov Avatar answered Oct 16 '22 00:10

Vitya Shurapov