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:
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.