首页 > 解决方案 > Would I run into any problems with having protocols with shared requirements?

问题描述

protocol House {
    var name : String {get set}
    func changeAddress()
}

protocol Person {
    var name : String {get set}
    func changeAddress()
}

class Something : Person, House {
    var name : String

    init (name: String){
        self.name = name
    }
    func changeAddress(){

    }
}

Likely I'm not going to do anything like this. But I'm asking this question because I'm getting no warning or anything for this. Isn't this a bug? ie the protocol witness table is conforming to two requirements through one conformance and it's hiding some of its variables, had I just changed the variable to something id on one of the protocols then the requirements would have been different, doesn't this at least merit a warning? and then maybe having it silenced by something like @sharedPWT :D

Isn't this code smell in it's nature? Or there are circumstances where this can actually be helpful?

标签: swiftprotocolscompositionswift-protocols

解决方案


您的见证表想法是一条红鲱鱼,因为没有代码也没有调度。它比这简单得多。这两个协议都只是关于如何构造采用类型的说明;他们说“做这个”,在你的采用者身上你做那个,所以你符合这两个要求。没问题。

如果这些是具有扩展和实现的方法,那么现在我们有话要说!例如:

protocol A {
    func f()
}
extension A {
    func f() { print("A")}
}
protocol B {
    func f()
}
extension B {
    func f() { print("B")}
}
class C:A,B {} // compiler stops you, rightly

这段代码不是天生就有味道吗?或者在某些情况下这实际上会有所帮助?

这不是一个难闻的气味,事实上,在非常真实的意义上,这种事情在整个标准库中一直在发生。毕竟,协议层次结构是什么,而不是您正在概述的事情的一个例子?说协议 P2 采用协议 P1 只是说 P1 需要什么,P2 也需要什么。


推荐阅读