美文网首页
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)

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