Skip to content

Instantly share code, notes, and snippets.

@SpacyRicochet
Last active February 9, 2019 12:13
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SpacyRicochet/88a1553ea931e867923d to your computer and use it in GitHub Desktop.
Save SpacyRicochet/88a1553ea931e867923d to your computer and use it in GitHub Desktop.
Extension of protocol cannot have inheritance clause
protocol Money {
var value: Double { get }
var inGold: Double { get }
var symbol: String { get }
}
// Sadly, gives a compiler error.
// "Extension of protocol 'Money' cannot have an inheritance clause"
extension Money: CustomStringConvertible {
var description: String {
return "\(value)\(symbol)"
}
}
// This works though. Compiles fine.
protocol Money: CustomStringConvertible {
var value: Double { get }
var inGold: Double { get }
var symbol: String { get }
}
extension Money {
var description: String {
return "\(value)\(symbol)"
}
}
@eMdOS
Copy link

eMdOS commented Jul 19, 2017

It is because a constraint is needed for conformance purposes, otherwise, the compiler thinks it is an inheritance.

I'm unsure the following code covers your needs, so it could be something like:

protocol Money {
    var value:  Double { get }
    var inGold: Double { get }
    var symbol: String { get }
}

// Removed error:  ... "Extension of protocol 'Money' cannot have an inheritance clause"
extension Money where Self: CustomStringConvertible {
    var description: String {
        return "\(value)\(symbol)"
    }
}

I hope this will be helpful.

@hamsternik
Copy link

Thanks a lot, @eMdOS. Your solution is correct.

@lochiwei
Copy link

lochiwei commented Jan 6, 2019

I think you have to let protocol Money inherit from CustomStringConvertible in the first place:

protocol Money: CustomStringConvertible {
    var value:  Double { get }
    var inGold: Double { get }
    var symbol: String { get }
}

and then, add the following protocol extension:

extension Money {
    var description: String {
        return "\(value)\(symbol)"
    }
}

a working example: struct Diamond: Money

I'm not sure whether I'm right or not, so tell me if I'm wrong.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment