Self property in Methods

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.

Example:

Swift




class calculate 
{  
let x: Int  
let y: Int  
let res: Int  
init(x: Int, y: Int
{  
self.x = x  
self.y = y  
res = x + y  
print("Result Inside Self Block: \(res)")  
}  
func tot(z: Int) -> Int {  
return res - z  
}  
func result() 
{  
print("Result is: \(tot(z: 10))")  
print("Result is: \(tot(z: 30))")  
}  
}  
let pri = calculate(x: 500, y: 100)  
let sum = calculate(x: 200, y: 600)  
pri.result()  
sum.result()


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