Methods in Swift

Methods are functions which do functionality and task. Classes, Structures, and Enumeration can all have methods or functions in Swift. We all aware of that Structures and Enumerations in Objective C cannot define methods. Swift has a nice ability to define functions in Structure and Enumeration Type.

Two types methods are there in Swift just like other programming languages.

  1. Instance Method
  2.  Type Method or Class Method

Instance Methods:

Instance methods can be accessed through the object or instance of a particular class, structure or enumeration which means it belongs to the particular class, structure or enumeration type. An instance method can access properties and other instance methods of the same type. Instance method should be declared within the scope of its type. (between { and } of the class, structure or enumeration).

class Rectangle {

    let x = 0

    let y = 0

    let width = 100

    let height = 100

    func calculateArea() -> Int { // Instance method

        return width * height

    }

}

let rectangle = Rectangle() // Instance of the class, 

print("The area of a rectangle is \(rectangle.calculateArea)")

‘CalculateArea’ is an instance method which calculates the area of a rectangle. This method is accessed by an instance of a class.

Type Methods:

Swift has another type of method called Type Methods that can be accessed by using the type, not by the instance of the type. ‘static’ keyword in Swift is used to define Type Methods. Classes can also use ‘class’ keyword to allow its subclasses to override this method. Both instance method and type method use dot(.) syntax to access. But the major difference is instance methods are accessible by self or by the instance of that type whereas Type methods are accessible by Type itself.  To simplify our explanation below is the same sample code we have come across while studying instance method. Now we are just adding an extra method as classMethod with the static keyword.

class Rectangle {

    let x = 0

    let y = 0

    let width = 100

    let height = 100

    func calculateArea() -> Int {

        return width * height

    }

    static func classMethod() { //Type Method 

        print(“i am a type or Class method”)

    }

}

let rectangle = Rectangle()

print(“The area of a rectangle is \(rectangle.calculateArea)”) // accessing instance method

Rectangle.classMethod() // accessing class method.

Comments

comments

Leave a Reply

Your email address will not be published. Required fields are marked *