Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Methods
3.
Swift Method
3.1.
Example 1
3.2.
Output
3.3.
Example 2
3.4.
Output
4.
Swift static Methods
4.1.
Example
4.2.
Output
5.
Swift self property in Methods
5.1.
Example
5.2.
Output
6.
Swift mutating Methods
6.1.
Example: Modifying Value Types from Method
6.1.1.
Output
7.
Frequently Asked Questions
7.1.
Is swift a procedural language or an object-oriented language?
7.2.
Is Swift frontend or backend?
7.3.
In Swift, how do you make a property optional?
7.4.
What is Dictionary in Swift?
7.5.
In Swift, what are the various control transfer statements?
8.
Conclusion
Last Updated: Mar 27, 2024

Swift Methods

Author SHIVANGI MALL
0 upvote

Introduction

Swift is a multi-paradigm, object-oriented, functional, imperative, and block-structured general-purpose programming language. It also supports the concept of objects and classes, just as other oop languages. Swift is the outcome of the most recent programming language research and is designed utilizing Apple Inc.'s current approach to safety and software design standards for iOS, macOS, watchOS, and tvOS applications.

Swift is simple to learn, simple to use, safe, fast, and expressive. Swift development in the open has significant benefits since it can now be ported to a vast number of platforms, devices, and use cases.

Methods

Methods are functions that are linked to a specific type. Instance methods, which encapsulate specific duties and functionality for working with an instance of a certain type, can be defined by classes, structures, and enumerations. Type methods are related to the type and can be defined by classes, structures, and enumerations. In Objective-C, type methods are similar to class methods.

Swift distinguishes itself from C and Objective-C by allowing structures and enumerations to define methods. Classes are the only kinds in Objective-C that can define methods. You can define a class, structure, or enumeration in Swift while still having the freedom to define methods on the type you create.

Swift Method

A method is a Swift function that is declared within a class. For example,

class Student {
  . . .    
 
  // define methods
  func getrollno() {
  // method body    
  }
}

getrollno() is a method defined within the Student class in this case. Make sure you understand how classes and structs work in Swift before moving on to methods.

Example 1

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

var nick = Student()

// call method
nick.greet()

Output

Hey there!

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

Example 2

// create a class
class Rectangle {

  var length = 0.0
  var breadth = 0.0
  // method to calculate area
  func calculateArea() {
    print("Area of Rectangle =", length * breadth)
  }
 
  // method to calculate perimeter
  func calculateperi() {
    print("Perimeter of Rectangle =", 2*(length + breadth))
  }
}
  // create object of Rectangle class
  var rectangle1 = Rectangle()


  // assign values to all the properties 
  rectangle1.length = 42.5
  rectangle1.breadth = 30.8


  // access method inside class
  rectangle1.calculateArea()
  rectangle.calculateperi()

Output

Area of Rectangle = 1309.0
Perimeter of Rectangle = 1309.0

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

  • calculateArea()to compute the area of the rectangle
  • calculateperi()to compute the perimeter of the rectangle

We utilized the class's object rectangle1 to call these functions because they are declared inside the class.

rectangle1.calculateArea()
rectangle1.calculateperi()

Swift static Methods

We utilized objects of the class to access its methods in the previous example. We can, however, define methods that can be called without having to create objects.

Static methods are the name for these types of methods. To construct a static method in Swift, we use the static keyword. For example,

class Calculator {

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

Here, multiply() is the static method. The class name is used to access a static method. For example,

// access static method
Calculator.add()

Example

class Calculator {
  // non-static method
  func multiply(val1: Int, val2: Int) -> Int {
    return val1 * val2
  }
  // static method
  static func add(val1: Int, val2: Int) -> Int {
    return val1 + val2
   }
}
// create an instance of the Calculator class
var obj = Calculator()

// call static method
var result2 =  Calculator.add(val1: 5, val2: 3)
print("5 + 3 =", result2)

// call non-static method
var result1 = obj.multiply(val1:3,val2:6)
print("3 * 6 =", result1)

Output

5 + 3 = 8
3+ 6 = 18

In the preceding example, we constructed the Calculator class. Add() is a static method, and multiply() is a non-static method ()

Here,

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

We can access static methods using class names since they are of class type (connected with a class rather than an object).

Swift self property in Methods

Every type of instance has an implicit property called self that is the same as the instance itself. Within its own instance methods, you utilize the self property to refer to the current instance.

Example

class Counter {
   var count = 0
   func increment() {
       self.count += 1
   }
 func increment(by amount: Int) {
     self.count += amount
  }
func reset() {
       count = 0
  }
}

You don't need to write self in your code very much in practice. When you use a known property or method name within a method and don't explicitly write self, Swift guesses you're referring to a property or method of the current instance. The use of count (rather than self.count) in the three Counter instance methods demonstrates this assumption.

The only exception to this rule is when an instance method's parameter name is the same as a property of that instance. In this case, the parameter name takes precedence, and the property must be referred to in a more qualified manner. The self property is used to distinguish between the parameter and property names.

class Person {

  var age = 0

  func checkEligibility(age: Int) {

    // using self property
    if (self.age < age) {
      print("Not Eligible for getting admission in college")
    }

    else {
      print("Eligible for getting admission in college")
    }
  }
}

var person1 = Person()
person1.age = 18
person1.checkEligibility(age: 50)

Output

Not eligible for getting admission in college 

The property and method parameters in the example above have the same name, age.

We used the self property inside the checkEligibility() method to distinguish between them.

Swift mutating Methods

If we declare properties inside a class or struct in Swift, we can't change them inside methods. For example,

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

Because struct is a value type, attempting to change the value of salary will result in an error.

However, we must use the mutating keyword when declaring a method if we want to modify the properties of a value type from within a method.

Example: Modifying Value Types from Method

struct Student {
  var marks = 0
  
  // define mutating function
  mutating func marksIncrement(increase: Int) {


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


var student1 = Employee()
student1.marks = 20
student1.marksIncrement(increase: 50)

Output

Increased Marks: 70

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

mutating func marksIncrement(increase: Int) {

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

The mutating method allows us to change the value of the mark within the method.

Frequently Asked Questions

Is swift a procedural language or an object-oriented language?

Swift is an inherited language from C and Objective-C that may be used as a procedural or object-oriented language. Class is an object-oriented programming language notion.

 

Is Swift frontend or backend?

We can use Swift to build software that runs on the client (frontend) and the server (backend).

 

In Swift, how do you make a property optional?

To make a property optional, we must use the question mark??' in the code. If a property has no value, the symbol? can be used to avoid a runtime error.

 

What is Dictionary in Swift?

The key-value pairs are stored in Swift Dictionary, and the value is accessed by using the key. In other programming languages, hash tables are similar.

 

In Swift, what are the various control transfer statements?

The control transfer statements in Swift are as follows:

  • Continue
  • Break
  • Fallthrough
  • Return

Conclusion

In this article, we have extensively discussed Swift methods.

We hope that this blog has provided you with new information. And if you're interested in learning more, see our posts on Object-Oriented ProgrammingClasses, and ObjectsByte Class in JavaCharacter Class in Java,  Difference Between Procedural and Object Oriented Programming, Best DevOps Tools To Get Acquainted With. Please vote for our blog to help other ninjas succeed.

Visit our practice platform Coding Ninjas Studio to practice top problems, attempt mock tests, read interview experiences, and much more.!

Happy Reading!

Live masterclass