Modifying Value Types from Instance Methods

Structures and enumerations are value types in the Swift 4 language, meaning that instance methods cannot change them. Swift 4 language, on the other hand, offers flexibility to change the value types by “mutating” behaviour. After the instance methods have been executed, mutate will make any changes and then revert to the initial state. Additionally, a new instance is created for the implicit function by the “self” property, which replaces the current method after it has been used.

Swift




struct area 
{  
var length = 1  
var breadth = 1  
func area() -> Int {  
return length * breadth  
}  
mutating func scaleBy(res: Int
{  
length *= res  
breadth *= res  
print(length)  
print(breadth)  
}  
}  
var val = area(length: 2, breadth: 4)  
val.scaleBy(res: 3)  
val.scaleBy(res: 30)  
val.scaleBy(res: 300)


Output:

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.

Similar Reads

Instance Methods

Classes, structures, and enumeration instances can be accessed using Swift instance methods. To access and modify instance properties, instance methods provide functionality relevant to the instance’s need. The curly braces can be used to write the instance method. It has implicit access to the type instance’s methods and properties. It will have access to that specific instance of the type when it is called....

Local and External Parameter Names

...

Self property in Methods

In Swift, functions can describe their variables’ local and global declarations. For functions and methods, the characteristics of local and global parameter name declarations vary. For convenience, the first parameter in Swift  is referred to by the prepositions “with,” “for,” and “by.”...

Modifying Value Types from Instance Methods

...

Self Property for Mutating Method

All instances of the defined type have a property called “self” that is implicit in methods. To refer to the current instances of its defined methods, use the “Self” property....

Type Methods

...

Contact Us