我怎样才能“明确地"快速实施协议?如果不可能,为什么? [英] How can I "explicitly" implement a protocol in swift? If it is impossible, why?

查看:34
本文介绍了我怎样才能“明确地"快速实施协议?如果不可能,为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 C# 中,有这个很棒的语言功能,称为显式接口实现",允许您实现两个或多个接口方法名称冲突的接口.当您使用封闭类型的对象调用它时,它还可以使方法做一件事,当您将其转换为接口类型然后调用该方法时,它可以做另一件事.我想知道 Swift 中是否有这样的东西.这是否与斯威夫特的任何意识形态冲突?

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"

我发现了这个在 Internet 上,但我认为这无关紧要,因为它似乎与强制子类中的方法覆盖有关.

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.

推荐答案

协议扩展基本上已经完成了你所描述的:

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

这篇关于我怎样才能“明确地"快速实施协议?如果不可能,为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆