YouTip LogoYouTip

Swift Methods

Swift methods are functions that are associated with a particular type. In Objective-C, classes are the only types that can define methods. In Swift, however, you can choose whether to define a class/structure/enum, and you can also flexibly define methods on the types (classes/structures/enums) you create. * * * ## Instance Methods In the Swift language, instance methods are methods that belong to a particular instance of a class, structure, or enumeration type. Instance methods provide the following capabilities: * Access and modify instance properties * Provide functionality related to the instance's purpose Instance methods must be written within the opening and closing braces ({}) of the type they belong to. Instance methods can implicitly access all other instance methods and properties of their type. Instance methods can only be called by a specific instance of the class they belong to. Instance methods cannot be called apart from an existing instance. ### Syntax func funcname(Parameters) -> returntype { Statement1 Statement2 …… Statement N return parameters } ### Instance import Cocoaclass Counter { var count = 0 func increment() { count += 1 } func incrementBy(amount: Int) { count += amount } func reset() { count = 0 }}// The initial count value is 0let counter = Counter()// The count value is now 1 counter.increment()// The count value is now 6 counter.incrementBy(amount: 5)print(counter.count)// The count value is now 0 counter.reset()print(counter.count) The output of the above program execution is: 60 The Counter class defines three instance methods: * **increment** increments the counter by 1; * **incrementBy(amount: Int)** increments the counter by a specified integer value; * **reset** resets the counter to 0. The **Counter** class also declares a mutable property **count** to keep track of the current counter value. * * * ## Local and External Parameter Names for Methods Swift function parameters can have both a local name (used inside the function body) and an external name (used when calling the function Methods in Swift are very similar to methods in Objective-C. Just like in Objective-C, the name of a method in Swift typically uses a preposition to refer to the first parameter, such as: with, for, by, etc. Swift defaults to giving only a local parameter name to the first parameter name of a method; by default, it gives both a local and external parameter name to the second and subsequent parameter names. In the following instance, 'no1' is declared as a local parameter name in Swift. 'no2' is used for global declaration and accessed by external programs. import Cocoaclass division { var count: Int = 0 func incrementBy(no1: Int, no2: Int) { count = no1 / no2 print(count) }}let counter = division() counter.incrementBy(no1: 1800, no2: 3) counter.incrementBy(no1: 1600, no2: 5) counter.incrementBy(no1: 11000, no2: 3) The output of the above program execution is: 6003203666 ### Modifying External Parameter Names We force the addition of an external name to the first parameter, using this local name as the external name (prior to Swift 2.0, the # sign was used). Conversely, we can also use an underscore (_) to set the second and subsequent parameters to not provide an external name. import Cocoaclass multiplication { var count: Int = 0 func incrementBy(first no1: Int, no2: Int) { count = no1 * no2 print(count) }}let counter = multiplication() counter.incrementBy(first: 800, no2: 3) counter.incrementBy(first: 100, no2: 5) counter.incrementBy(first: 15000, no2: 3) The output of the above program execution is: 240050045000 * * * ## The self Property Every instance of a type has an implicit property called self, which is exactly equivalent to the instance itself. You can use this implicit self property in an instance method of an instance to refer to the current instance. import Cocoaclass calculations { let a: Int let b: Int let res: Int init(a: Int, b: Int) { self.a = a self.b = b res = a + b print("Inside Self: \(res)") } func tot(c: Int) -> Int { return res - c } func result() { print("Result is: \(tot(c: 20))") print("Result is: \(tot(c: 50))") }}let pri = calculations(a: 600, b: 300)let sum = calculations(a: 1200, b: 300) pri.result() sum.result() The output of the above program execution is: Inside Self: 900Inside Self: 1500Result is: 880Result is: 850Result is: 1480Result is: 1450 * * * ## Modifying Value Types from Within Instance Methods Structures and enumerations are value types in Swift. Generally, the properties of a value type cannot be modified within its instance methods. However, if you do need to modify the properties of a structure or enumeration within a specific method, you can choose to mutate that method, and then the method can change its properties from within; and any changes it makes will remain in the original structure when the method ends. The method can also assign a completely new instance to its implicit self property, and this new instance will replace the original one after the method ends. import Cocoastruct 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: 3, breadth: 5) val.scaleBy(res: 3) val.scaleBy(res: 30) val.scaleBy(res: 300) The output of the above program execution is: 91527045081000135000 * * * ## Assigning to self Within a Mutating Method Mutating methods can assign a completely new instance to the implicit self property. import Cocoastruct area { var length = 1 var breadth = 1 func area() -> Int { return length * breadth } mutating func scaleBy(res: Int) { self.length *= res self.breadth *= res print(length) print(breadth) }}var val = area(length: 3, breadth: 5) val.scaleBy(res: 13) The output of the above program execution is: 3965 * * * ## Type Methods Instance methods are methods called by an instance of a type. You can also define methods that are called on the type itself, and these kinds of methods are called type methods. To declare type methods for structures and enumerations, add the keyword static before the func keyword of the method. Classes may use the keyword class to allow subclasses to override the parent class's implementation of the method. Type methods are called using dot (.) syntax just like instance methods. import Cocoaclass 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: -35)let num = absno.abs(number: -5)print(no)print(num) The output of the above program execution is: 355
← Swift SubscriptsSwift Properties β†’