Explain the difference between functions and Methods in Swift


As an iOS developer, it is imperative to understand the difference between functions and methods in the Swift language.

It might be confusing for you to understand the difference between function and method, but you might be thinking they are both the same. That's not true. They have some differences between them. Let's understand it in this article.

  • In the Swift language, simply the methods are used in class, struct, and enum. While functions are defined independently. Basically, you can create a function anywhere in the code without creating a class or structure.

  • Simply, we can say that each method is a function while each function is not a method.

What functions do?

Basically, functions are used to perform specific actions and are called by their names. It is very simple to pass the variables or constants as an argument while calling a function. Also, we can return a value from a function of any type. A function that works independently of a file can also be defined outside of it.

Syntax

func functionName(parameters...) -> returnType {
   // write statements here to perform actions
}

Example

func performTaskAfter(_ seconds: Double, completionHandler: @escaping () -> ()?) {
   // perform an async action after given delay
   // .now() + seconds: adding given seconds in current time
   DispatchQueue.main.asyncAfter(deadline: .now() + seconds) {
      completionHandler?()
   }
}

Explanation

In the above example, we defined a function called performTaskAfter to perform a task after some delay given in seconds. This function can be defined anywhere in the code and you can call it from anywhere in the code.

What Methods do?

We know that every method is a function and can be defined in classes, structures, and enumerations. Using methods, we can perform certain actions according to your requirements. As per your needs, you can define more than one method to perform different tasks.

Now, you have to create an object to access the defined methods in a class or structure. Using that object, you can call methods to perform tasks. You can pass arguments while calling the method. You should note that without creating an object of that class or struct you cannot access the methods.

In the Swift language, there are two types of methods like the following −

  • Instance Methods − As per their names, these are the instance-specific methods that can be called through the instances. The compiler will give you an error if you will try to access the methods without an instance of that class or struct. Also, you cannot call the methods of a class (for eg. Class Student) from another class's instance.

  • Type Methods − In Swift, you can define the type methods with prefix keywords like static or class. There is no need to create an instance of a class or struct to call type methods. They can be called directly from the type name.

Example

struct Student {
    
   let name: String
   let grade: Int
    
   // Instance method
   func displayInfo() {
      print("name: \(name)")
      print("grade: \(grade)")
   }
    
   // Type method
   static func dummyStudents() -> [Student] {
      return [Student(name: "Ray Sin", grade: 4),
         Student(name: "Cherry Blossom", grade: 2),
         Student(name: "Perry Scope", grade: 7)]
   }
}
let anne = Student(name: "Anne Teak", grade: 5)
// calling instance method from object anne
anne.displayInfo()

// calling type method
let students = Student.dummyStudents()
print("number of students: ", students.count)

Output

name: Anne Teak
grade: 5
number of students:  3

Explanation

In the above example, we have created two different methods: namely displayInfo() and dummyStudents(). We can see that the first method is an instance method that is accessed via an instance while the second method is called by the class Student itself.

Visual identification between Function and Method in Swift

The Swift language shows how a function and method are denoted. It is clearly visible that both are denoted as follows −

  • The function has an icon like ƒ

  • The method has an icon of M

Summarize the between Function and Method in Swift
Function Method
The function is defined as independent. So that, we can define functions outside of the class. They are connected with a class or struct itself. Outside the scope, you can not define the methods.
Functions are independent properties of structured languages like C/C++. Methods works within the scope of an object similar to Object-oriented languages like C#, Java, Swift, etc.
Functions don't capture any reference variables or constants. Methods are called using reference variables (or instances) only.
While functions do not belong to classes, they perform individually. Methods are defined to manipulate the particular instance of that class or struct.
No need to create objects to call them. An object is required to access them.
Simply, every function is not a method. While every method is a function.

Conclusion

Swift provides functions and methods that serve different purposes. The differences between them are explained in this article, even though you may think they are the same.

Updated on: 21-Dec-2022

374 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements