美文网首页
swift3 基础语法(mutating)

swift3 基础语法(mutating)

作者: march_1991 | 来源:发表于2016-08-04 11:24 被阅读110次

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

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去掉,则会报错不能改变结构体的成员。

相关文章

  • swift3 基础语法(mutating)

    //再看官网的 时候看见这个关键字 很疑惑 protocol ExampleProtocol { var simp...

  • 【Swift3基础】基础语法

  • Swift3+MVVM+ReactiveCocoa5实战1

    关于Swift3 14年苹果公司推出Swift语言,过程中语法不间断地变,后来Swift3大版本出来,语法稳定了很...

  • iOS之swift学习笔记

    swift的基础语法 这样吧,先把swift4.0教材的先分享给大家。swift4和swift3的基本上没有多大的...

  • Swift: 你好, AutoLayout!

    Xcode8已经发布,带了Swift3的预览版本,以后都是默认采用Swift3的语法。 这个例子主要是演示iOS中...

  • swift3练手

    这个文件需要swift3和xcode8 beta6才能run,本身比较简单,为了试一下swift3的新语法,swi...

  • Swift Tour Learn (十一) -- Swift 语

    本章将会介绍 协议语法属性要求方法要求(Method Requirements)Mutating 方法要求构造器要...

  • xcode8和swift3

    xcode8正式版本可以下载了,里面搭载了swift3。swift3和swift2语法是不兼容的,所以旧代码需要转...

  • 协议(protocol)

    协议语法 遵守协议的格式 属性要求 例子 协议中定义类型属性 例子 方法要求 例子 Mutating方法要求 例子...

  • 【Android】知识点汇总,坚持原创ing

    Android基础 Java基础 Java基础——Java内存模型和垃圾回收机制 语法基础 语法基础——C语法基础...

网友评论

      本文标题:swift3 基础语法(mutating)

      本文链接:https://www.haomeiwen.com/subject/sfuajttx.html