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.
Syntax
func funcname(Parameters) -> returntype {
Statement1
Statement2
—
Statement N
return parameters
}
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 } func tot(z: Int ) -> Int { return res - z } func result() { print ( "Result is: \(tot(z: 70))" ) print ( "Result is: \(tot(z: 90))" ) } } let pri = calculate(x: 400, y: 500) pri.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.