Type Methods
An instance method is used when a specific instance of a method is called; Additionally, the method is referred to as a “Type Method” when it calls a particular type of method. The “func” keyword is used to define type methods for “classes,” while the “static” keyword precedes the “func” keyword to define type methods for “structures” and “enumerations.”
The “.” syntax is used to access and call type methods, which invokes the entire method rather than just one specific instance.
Swift
class Math { class func abs (number: Int ) -> Int { if number < 0 { return (-number) } else { return number } } } struct absno { static func abs (number: Int ) -> Int { if number < 0 { return (-number) } else { return number } } } let no = Math. abs (number: -20) let num = absno. abs (number: -15) print (no) print (num) |
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.