首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >当类符合包含变异函数的协议时,会发生什么情况?

当类符合包含变异函数的协议时,会发生什么情况?
EN

Stack Overflow用户
提问于 2016-04-29 13:00:38
回答 1查看 1.7K关注 0票数 1

我只是在试验Swift的协议编程。在此期间,我遇到了以下场景。假设我们有这样的协议,

代码语言:javascript
复制
protocol SomeProtocol {
    .....
    mutating func mutatingFunc()
    .....
}

现在假设我有一个名为MyClass的类,它与我的SomeProtocol类似,

代码语言:javascript
复制
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)
    }
}

假设我有另一种结构&另一种协议,

代码语言:javascript
复制
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
    }

}

所以现在我的观察是,

  1. 对于一个类,函数在协议中是否被提到是变异并不重要,而且我们从来不允许将类中的方法称为变异。
  2. 对于一个结构,如果已实现的方法不修改成员,我们不需要提到func在协议中变异甚至很难。
  3. 对于一个结构,如果我们将协议方法实现为变异func,如果我们没有将该方法指定为在协议中更改func。编译器会产生错误。

目前,由于上述情况,我对编译器处理结构的方式感到困惑。如果有人能解释在协议中突变功能的重要性,即“当我们将协议中的func声明为变异时,我们是否应该在实现它时使func发生变异?”会很棒也很有帮助的。

我知道什么是变异函数,我只是混淆了协议中定义的变异方法。

提前谢谢。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-04-29 13:06:08

我不明白什么是“混乱”。你已经完美地阐明了规则!结构可以将协议的mutating函数实现为非变异,但不能将协议的非变异功能实现为mutating。一旦你说出了这些规则,就没有什么好“困惑”的了。规则就是规则。

类没有变异函数,所以您的研究有点不相干。如果您已将协议声明为class协议,则协议中的mutating注释将是非法的。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36939049

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档