swift3.0 method declaration in the protocol is mutating

Source: Internet
Author: User

Http://www.pdosgk.com/index.php/home/news/show/id/70159.html

To declare a protocol method as mutating

Swift's protocol can be implemented not only by class type, but also by struct and enum. For this reason, we need to think more about using mutating to decorate a method when we write to someone else's protocol, such as mutating Func MyMethod (). Swift's mutating keyword modification is designed to modify the struct or enum variables in the method, so if you don't write mutating in the protocol, if someone uses struct or an enum to implement the protocol, they can't change the method from Own variables. Like the following code

Protocol Vehicle {
    var numberofwheels:int {get}
    var color:uicolor {Get Set}
    mutating func () ChangeColor >

struct Mycar:vehicle {let
    numberofwheels = 4
    var color = uicolor.blue mutating func changecolor
    () {
  color =. Red
    }
}

If the protocol definition of mutating removed, Mycar will not be able to compile: to keep the existing code unchanged, it will be reported that there is no implementation of the Agreement; If you remove mutating, you will not be able to change the structure of the member. The sad eyes of the user of this agreement, I believe you can imagine.

In addition, when using class to implement a protocol with a mutating method, the implementation is preceded by a mutating modification, because class can change its own member variables at will. Therefore, in the protocol with mutating modification method, the implementation of class is completely transparent, can be regarded as non-existent.

Class Myferrari:vehicle {let
    numberofwheels = 4
    var color = uicolor.red
    func changecolor () {
        color =. BL Ack
    }
}

Remember the conclusion that all the methods in the protocol are decorated with mutating

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.