Methods by Example - Swift Programming Language

  • Methods are functions that are associated with a particular type.
  • Classes, structures, and enumerations can all define instance methods, which encapsulate specific tasks and functionality for working with an instance of a given type.
  • Classes, structures, and enumerations can also define type methods, which are associated with the type itself.

1. Instance Methods

  • Instance methods are functions that belong to instances of a particular class, structure, or enumeration.
  • They support the functionality of those instances, either by providing ways to access and modify instance properties, or by providing functionality related to the instance’s purpose.
  • You write an instance method within the opening and closing braces of the type it belongs to.
  • An instance method has implicit access to all other instance methods and properties of that type.
  • An instance method can be called only on a specific instance of the type it belongs to. It cannot be called in isolation without an existing instance.
class Counter {
    var count = 0
    func increment() {
        count += 1
        print("value of count in increment() func is ",count)
    }
    func increment(by amount: Int) {
        count += amount
         print("value of count in increment(by:) func is ",count)
    }
    func reset() {
        count = 0
         print("value of count in reset func is ",count)
    }
}
let counter = Counter()
counter.increment()
counter.increment(by: 5)
counter.reset()

/* prints:
value of count in increment() func is  1
value of count in increment(by:) func is  6
value of count in reset func is  0
*/

1.1 The self Property

  • Every instance of a type has an implicit property called self, which is exactly equivalent to the instance itself.
  • You use the self property to refer to the current instance within its own instance methods.
class 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 Block: \(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()

/* results
Inside Self Block: 900
Inside Self Block: 1500
Result is: 880
Result is: 850
Result is: 1480
Result is: 1450
*/

1.2 Modifying Value Types from Instance Methods

  • In Swift 4 language structures and enumerations belong to value types which cannot be altered by its instance methods.
  • However, Swift 4 language provides flexibility to modify the value types by mutating behavior.
struct 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)
/* results:
9
15
270
450
81000
135000 */

1.3 Assigning to self Within a Mutating Method

  • Mutating methods can assign an entirely new instance to the implicit self property.
struct 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 val1 = Area(length: 3, breadth: 5)
val1.scaleBy(res: 13)

/* results:
39
65
*/

2.Type Methods

  • Type methods for classes are defined with the class keyword before the func keyword and structures and enumerations type methods are defined with the static keyword before the func keyword.
  • Type methods are called and accessed by . syntax where instead of calling a particular instance the whole method is invoked.
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: -35)
let num = absno.abs(number: -5)

print(no)
print(num)

/* results:
35
5 */

Next - Access Control by Example


You can download the swift playground of all above examples from Here



Share Tweet Send
0 Comments
Loading...
You've successfully subscribed to Developer Insider
Great! Next, complete checkout for full access to Developer Insider
Welcome back! You've successfully signed in
Success! Your account is fully activated, you now have access to all content.