Swift Methods

A Swift function defined inside a class is called method. For example,

class Person {
  . . .    
 
  // define methods
  func greet() {
  // method body    
  }
}

Here, greet() is a method defined inside the Person class. Before you learn about methods, make sure you know the working of class and struct in Swift.


Example 1: Swift Methods

class Person {
  
  // define a method
  func greet() {
    print("Hey there!")
  }
}

var nick = Person()

// call method
nick.greet()

Output

Hey there!

In the above example, we have created a method named greet() inside the Person class. Here, we have used the object nick of the class to call the method.

// call method
nick.greet()

The greet() method simply prints the string "Hey there!" inside it.


Example 2: Calculate Area and Volume using Swift Methods

// create a class
class Hall {

  var length = 0.0
  var breadth = 0.0
  var height = 0.0

  // method to calculate area
  func calculateArea() {
    print("Area of Hall =", length * breadth)
  }

  // method to calculate volume
  func calculateVolume() {
    print("Volume of Hall =", length * breadth * height)
  }
}

// create object of Hall class
var hall1 = Hall()

hall1.length = 42.5
hall1.breadth = 30.8
hall1.height = 45.2

// call calculateArea() method
hall1.calculateArea()

// call calculateVolume() method
hall1.calculateVolume()

Output

Area of Room = 1309.0
Volume of Room = 59166.8

In the above example, we have created a class named Hall with two methods:

  • calculateArea() - to compute the area of the hall
  • calulateVolume() - to compute the volume of the hall

Since these methods are declared inside the class, we have used the object hall1 of the class to call them.

hall1.calculateArea()

hall1.calculateVolume()

Swift static Methods

In the previous example, we have used objects of the class to access its methods. However, we can also create methods that can be accessed without creating objects.

These types of methods are called static methods. In Swift, we use the static keyword to create a static method. For example,

class Calculator {

  // static method 
  static func add() {
  ...  
  }
}

Here, add() is the static method.

To access a static method, we use the class name. For example,

// access static method
Calculator.add()

Example: Swift static Methods

class Calculator {

  // non-static method
  func multiply(num1: Int, num2: Int) -> Int {
    return num1 * num2
  }

  // static method
  static func add(num1: Int, num2: Int) -> Int {
    return num1 + num2
   }
}

// create an instance of the Calculator class
var obj = Calculator()

// call static method
var result2 =  Calculator.add(num1: 2, num2: 3)
print("2 + 3 =", result2)

// call non-static method
var result1 = obj.multiply(num1:2,num2:2)
print("2 * 2 =", result1)

Output

2 * 2 = 4
2 + 3 = 5

In the above example, we have created a class named Calculator. The class contains static method: add() and non-static method - multiply()

Here,

  • Calculator.add() - calls static method using the class name
  • obj.multiply() - calls a non-static method using the object of the class.

A static method is of class type (associated with class rather than object), so we are able to access them using class names.

Note: Similarly, we can also create static methods inside a struct. static methods inside a struct are of struct type, so we use the struct name to access them.


Swift self property in Methods

Sometimes the name of a property and the name of a method parameter might be the same. For example,

var physics = 0

func checkEligibility(physics: Int) {
... 
}

Here, both the property and the method parameter have the same name physics.

In such cases there might be ambiguity between the names. So to distinguish between them, we use the self property. The self property refers to the current object of the method.


Example: Swift self property

class Marks {

  var physics = 0

  func checkEligibility(physics: Int) {

    // using self property
    if (self.physics < physics) {
      print("Not Eligible for admission")
    }

    else {
      print("Eligible for admission")
    }
  }
}

var student1 = Marks()
student1.physics = 28
student1.checkEligibility(physics: 50)

Output

Not eligible for admission

In the above example, we have used the same name physics for the property and method parameters.

To distinguish between them, we have used the self property inside the checkEligibility() method

if (self.physics < physics) {
  ...
}

Here,

  • self.physics - refers to the property of the student1 object with value 28.
  • physics - refers to the method parameter with value 50.

Since the condition (28 < 50) is true, the statement inside if is executed.


Swift mutating Methods

In Swift, if we declare properties inside a class or struct, we cannot modify them inside the methods. For example,

struct Employee {

  var salary = 0.0
  ...
  func salaryIncrement() {
    // Error Code
    salary = salary * 1.5
  }

Here, since struct is a value type, if we try to modify the value of salary, we'll get an error message.

However, if we want to modify the properties of a value type from the inside of a method, we need to use the mutating keyword while declaring a method.


Example: Modifying Value Types from Method

struct Employee {
  var salary = 0
  
  // define mutating function
  mutating func salaryIncrement(increase: Int) {

  // modify salary property  
  salary = salary + increase
  print("Increased Salary:",salary)
  }
}

var employee1 = Employee()
employee1.salary = 20000
employee1.salaryIncrement(increase: 5000)

Output

Increased Salary: 25000

In the above example, we have created a struct named Employee. Notice,

mutating func salaryIncrement(increase: Int) {

  // modify salary property  
  salary = salary + increase
  ...
}

Here, the mutating method allows us to modify the value of salary inside the method.

Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges