Self Property for Mutating Method
A new instance of the defined method is given when mutating methods are combined with the “self” property.
Swift
struct area { var length = 1 var breadth = 1 func area() -> Int { return length * breadth } mutating func scaleBy(res: Int ) { self .length *= res self .breadth *= res print (length) print (breadth) } } var val = area(length: 6, breadth: 8) val.scaleBy(res: 11) |
Output:
Swift – Methods
Methods are functions that belong to a specific type. Instance methods, which encapsulate particular tasks and functionality for working with an instance of a given type, can be defined by classes, structures, and enumerations. Type methods, which are connected to the type itself, can also be defined by classes, structures, and enumerations. In Objective-C, type methods are comparable to class methods.
Swift differs significantly from C and Objective-C in that structures and enumerations can define methods, whereas classes are the only types in Objective-C that can. In Swift, you can define a class, structure, or enumeration and still define methods on the type you create.