iOS Programming Cookbook
上QQ阅读APP看书,第一时间看更新

Mutating instance methods

When you add instance methods, you can let them mutate (modify) the instance itself. In methods we've added before, we just do some logic and return a new value, and the instance value remains the same. With mutating, the value of instance itself will be changed. To do so, you have to mark your instance method with the mutating keyword. Let's take a look at an example:

extension Int{ 
   mutating func square(){ 
       self = self * self 
   } 
    
   mutating func double(){ 
       self = self * 2 
   } 
} 
 
var value = 8 
value.double() // 16 
value.square() // 256 

When you mark your method as mutating, it lets you to change self and assign new value to it.