swift3 基础语法(mutating)

//再看官网的 时候看见这个关键字  很疑惑

protocol ExampleProtocol {

var simpleDescription: String { get }

mutating func adjust()

}

//在struct  或enum 中

使用 mutating 关键字修饰方法是为了能在该方法中修改 struct 或是 enum 的变量,在设计接口的时候,也要考虑到使用者程序的扩展性。所以要多考虑使用mutating来修饰方法。

struct SimpleStruct: ExampleProtocol {

var simpleDescription: String = "A simple structure"

mutating func adjust() {

simpleDescription += "(adjusted)"

}

官网的提示Notice the use of the mutating keyword in the declaration of SimpleStructure to mark a method that modifies the structure. The declaration of SimpleClass doesn’t need any of its methods marked as mutating because methods on a class can always modify the class.

大概的意思就 :如果将ExampleProtocol中修饰方法的mutating去掉,编译器会报错说没有实现protocol。如果将struct中的mutating去掉,则会报错不能改变结构体的成员。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Chapters: Enumerations - Advanced Operators Excerpt From:...
    碧波浮沉阅读 680评论 0 1
  • 2014年5月23日中午,一场突如其来的大火,降临在苏格兰最美的艺术学院:格拉斯哥艺术学院,由查尔斯·雷尼·麦金托...
    毒设计阅读 3,430评论 0 0
  • 一到假期,内心骚动。女儿说:“妈妈还不带我去玩啊,如果我现在不去感受世界,如何成长?”对的,一直觉得,人应该去...
    李美霞素简纹绣阅读 779评论 0 1
  • 【七律(新韵)】 送2016年/大漠 漆漆寒夜清清月,独对三更冷冷灯。 岁岁奔忙常碌碌,年年回首总匆匆。 漂漂塞外...
    大漠qxy阅读 277评论 4 7
  • 用户研究,既要结果,也需过程,作用有二(1)方便测试/访谈结束后回顾整理,(2)必要时呈现一手资料给需求方。于是找...
    乔溪阅读 1,035评论 0 5