Swift and mutating struct

后端 未结 8 1688
鱼传尺愫
鱼传尺愫 2020-12-04 06:54

There is something that I don\'t entirely understand when it comes to mutating value types in Swift.

As the \"The Swift Programming Language\" iBook states:

8条回答
  •  有刺的猬
    2020-12-04 07:29

    SWIFT : Use of mutating function in Structs

    Swift programmers developed Structs in such a way that properties of it can not be modified within Struct methods. For example, Check the code given below

    struct City
    {
      var population : Int 
      func changePopulation(newpopulation : Int)
      {
          population = newpopulation //error: cannot modify property "popultion"
      }
    }
      var mycity = City(population : 1000)
      mycity.changePopulation(newpopulation : 2000)
    

    On executing the above code we get an error because we are trying to assign a new value to the property population of the Struct City. By default Structs properties can’t be mutated inside its own methods. This is how Apple Developers have built it, so that the Structs will have a static nature by default.

    How do we solve it? What’s the alternative?

    Mutating Keyword :

    Declaring function as mutating inside Struct allows us to alter properties in Structs. Line No : 5, of the above code changes to like this,

    mutating changePopulation(newpopulation : Int)
    

    Now we can assign the value of the newpopulation to property population to within the scope of the method.

    Note :

    let mycity = City(1000)     
    mycity.changePopulation(newpopulation : 2000)   //error: cannot modify property "popultion"
    

    If we use let instead of var for Struct objects, then we can’t mutate the value of any properties, Also this is the reason why we get an error when we try to invoke mutating function using let instance. So it is better to use var whenever you are changing value of a property.

    Would love to hear your comments and thoughts…..

提交回复
热议问题