How can I "explicitly" implement the protocol in swift? If this is not possible, why?

C # has this nifty language feature called "explicit interface implementations" that lets you implement two or more interfaces, where the method names of the interfaces interact. It can also make a way to do one thing when you call it using an object of the incoming type, and do another when you apply it to an interface type and then call the method. I am wondering if there is such a thing about Swift. Does this contradict any quick ideology?

Basically I want to do something like this:

struct Job: CustomStringConvertible {
    var location: String
    var description: String
    var CustomStringConvertible.description: String {
        return "Work Location: \(self.location), description: \(self.description)"
    }
}

Job(location: "Foo", description: "Bar").description // "Bar"
(Job(location: "Foo", description: "Bar") as CustomStringConvertible).description // "Work Location: Foo, description: Bar"

      

I found this on the internet, but I don't think it is relevant because it looks like a forced override method in child classes.

+3


source to share


1 answer


Protocol extensions basically do what you describe already:



protocol Cat {
}
extension Cat {
    func quack() {
        print("meow")
    }
}
class Duck : Cat {
    func quack() {
        print("quack")
    }
}
let d = Duck()
d.quack() // quack
(d as Cat).quack() // meow

      

+3


source







All Articles