Swift - Custom Type Instance Methods

Introduction

An instance method is a function that belongs to a particular instance of a class.

The following Truck class has four instance methods- accelerate() , decelerate() , stop() , and printSpeed() :

class Truck {
   var speed = 0

    func accelerate() {
       speed += 10
      if speed > 80 {
          speed = 80
       }
       printSpeed ()
   }

    func decelerate() {
       speed -= 10
       if speed<0 {
            speed = 0
         }
         printSpeed ()
     }

      func stop() {
        while speed>0 {
           decelerate ()
         }
      }

      func printSpeed() {
         print("Speed: \(speed)")
      }
}

To call the methods, you need to first create an instance of the Truck class:

var c = Truck ()

Once the instance has been created, you can call the methods using dot notation .

Demo

class Truck {
   var speed = 0/*from   w w  w  .  j a  v  a2 s  .  co m*/

    func accelerate() {
       speed += 10
      if speed > 80 {
          speed = 80
       }
       printSpeed ()
   }

    func decelerate() {
       speed -= 10
       if speed<0 {
            speed = 0
         }
         printSpeed ()
     }

      func stop() {
        while speed>0 {
           decelerate ()
         }
      }

      func printSpeed() {
         print("Speed: \(speed)")
      }
}
var c = Truck ()

c.accelerate()   //10
c.accelerate()   //20
c.accelerate()   //30
c.accelerate()   //40
c.decelerate()   //30
c.stop ()         //20

Result

Related Topic