仍然快速尝试,我遇到了这个问题(不确定它是否真的归类为一个)
所以我们有一个协议,以及一个继承它的结构。
protocol ExampleProtocol {
var simpleDescription: String { get }
func adjust()
}
struct SimpleStructure : ExampleProtocol{
var simpleDescription = "A simple structure"
mutating func adjust() {
simpleDescription += " (adjusted)"
}
func adjust() { //I created this second method just to conform to the protocol
}
}
var b = SimpleStructure()
b.adjust() //This generates a compiler error mentioning Ambiguity (Correct)
问题是如何调用mutating adjust()而不是调整协议。即我知道如果我将b声明为协议并将其初始化为它将调用协议的结构,但是如何调用第一个调整?还是不可能?或者我错误地使用它了吗?
干杯,
答案 0 :(得分:1)
您的代码无法编译,但错误在于通过添加adjust
属性重新定义mutating
方法 - 这不会创建{{1}的重载版本}。
在我看来,这是正确的代码:
adjust
表示:您必须在协议中将protocol ExampleProtocol {
var simpleDescription: String { get }
mutating func adjust()
}
struct SimpleStructure : ExampleProtocol{
var simpleDescription = "A simple structure"
mutating func adjust() {
simpleDescription += " (adjusted)"
}
}
函数定义为adjust
。