How can I “explicitly” implement a protocol in swift? If it is impossible, why?

无人久伴 提交于 2020-01-11 06:40:31

问题


In C#, there is this great language feature called "explicit interface implementations" that allows you to implement two or more interfaces where the names of the interfaces' methods conflict. It can also make a method do one thing when you call it using an object of the enclosing type, and do another thing when you cast it to the interface type then call the method. I am wondering if there is such a thing in Swift. Does this conflict with any of swift's ideologies?

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 that's relevant because it appears to be about forcing method overriding in child classes.


回答1:


Protocol extensions basically already do what you're describing:

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


来源:https://stackoverflow.com/questions/43743114/how-can-i-explicitly-implement-a-protocol-in-swift-if-it-is-impossible-why

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!