I've been trying to implement a protocol and protocol extension that provides a default == method in swift. Something like this:
protocol NameProtocol: Equatable {
func getName() -> String
}
extension NameProtocol{}
func ==<T: NameProtocol>(lhs: T, rhs: T) -> Bool{
return lhs.getName() == rhs.getName()
}
Then a class like this:
class NamedObject: NSObject, NameProtocol {
let name: String
init(name: String) {
self.name = name
super.init()
}
func getName() -> String {
return self.name
}
}
However, the custom == method is never called:
let one = NamedObject(name: "Name")
let two = NamedObject(name: "Name")
if one == two {
NSLog("EQUAL")
}
else{
NSLog("NOT EQUAL")
}
Am I doing something wrong here?
UPDATE:
From the answers I got it looks like what i'm trying to accomplish isn't really possible. The only way to come close is to subclass (which has its obvious drawbacks). I'm going to keep a lookout for a proper solution.
Aucun commentaire:
Enregistrer un commentaire