我只是在Swift中尝试协议编程。在此期间,我遇到了以下情况。 假设我们有一个像
这样的协议protocol SomeProtocol {
.....
mutating func mutatingFunc()
.....
}
现在假设我有一个名为MyClass的类,它符合我的SomeProtocol,
struct MyStruct {
var width = 0, height = 0
}
extension MyStruct: SomeProtocol {
//1. If I remove the mutating keyword from following method definition, compiler will give me error, that's understandable as we are modifying structure members
//2. Also note that, if I remove the mutating keyword while defining protocol & keep mutating keyword in the below method, the compiler will say that structure doesn't conform to protocol
mutating func mutatingMethod() {
width += 10
height += 10
}
}
class MyClass {
var width = 10
}
extension MyClass: SomeProtocol {
//1. However while implementing the protocol method in class, I can implement the same protocol method, and the compiler doesn't complaint even if I don't mention mutating keyword.
//2. But compiler will complain that mutating isn't valid on methods in classes or class-bound protocols, if I mention the mutating keyword
func mutatingMethod() {
width += 10
print(width)
}
}
假设我有另一种结构&另一个议定书,
protocol AnotherProtocol {
func nonMutatingFunc()
}
struct MyAnotherStruct {
var width = 0
}
extension MyAnotherStruct: SomeProtocol, AnotherProtocol {
func mutatingFunc() {
//1. Compiler is happy even without the mutating keyword as we are not modifying structure members, also the structure conforms to SomeProtocol.
print("Hello World")
}
mutating func nonMutatingFunc() {
//1. Compiler cries that we are not conforming to AnotherProtocol as the function is mutating
width += 10
}
}
现在我的观察是,
目前,由于上述情况,我对编译器对结构的行为方式感到困惑。如果有人能够解释在协议中改变函数的重要性,即“当我们将协议中的函数声明为变异时,我们是否应该在实现它时使func变异?”这真的很棒,乐于助人。
P.S。我知道变异函数是什么,我只是对协议中定义的变异方法感到困惑。
提前致谢。
答案 0 :(得分:3)
我看不出“混乱”是什么。你已经精美地阐明了这些规则!结构可以将协议的mutating
函数实现为非突变,但它可能不会将协议的非突变函数实现为mutating
。一旦你说出这些规则,就没有什么可以“混淆”了。规则就是规则。
类没有变异功能,所以你的调查有点无关紧要。如果您已将协议声明为class
协议,则协议中的mutating
注释将是非法的。