我只是在试验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声明为变异时,我们是否应该在实现它时使func发生变异?”会很棒也很有帮助的。
我知道什么是变异函数,我只是混淆了协议中定义的变异方法。
提前谢谢。
发布于 2016-04-29 13:06:08
我不明白什么是“混乱”。你已经完美地阐明了规则!结构可以将协议的mutating函数实现为非变异,但不能将协议的非变异功能实现为mutating。一旦你说出了这些规则,就没有什么好“困惑”的了。规则就是规则。
类没有变异函数,所以您的研究有点不相干。如果您已将协议声明为class协议,则协议中的mutating注释将是非法的。
https://stackoverflow.com/questions/36939049
复制相似问题