DEV Community

Neeraj Gupta for DSC CIET

Posted on

Extensions in Swift

Brief Introduction About Swift

Swift is a language developed by Apple which is made using modern approach, include safety features and software design patterns. As the name suggests swift is fast, safe and easy to use. It is basically made a replacement for c-based family(C, C++ and Objective-C). It can be used to make apps and can be also used for cloud services and it is among the fastest growing languages.

Extensions in Swift

Extensions add new functionality to an existing class, structure, enumeration, or protocol type. This includes the ability to extend types for which you do not have access to the original source code (known as retroactive modeling)”

Extensions in Swift can:

  1. Add computed instance properties and computed type properties

  2. Define instance methods and type methods

  3. Provide new initializers

  4. Define subscripts

  5. Define and use new nested types

  6. Make an existing type conform to a protocol

Syntax for Extension


extension someType {
// functionality to add goes here
}
Enter fullscreen mode Exit fullscreen mode

Coding Example on Extensions

Let's say i want some inbuilt function for integers to increment and decrement by one. Let's make one


extension Int {
    func incrementByOne() -> Int  {
        return (self + 1)
    }
    func decrementByOne() -> Int {
        return (self - 1)
    }
}

let number : Int = 2
print(number.incrementByOne()) //3
print(number.decrementByOne()) //1
Enter fullscreen mode Exit fullscreen mode

Here self refers to the value on which operation is done.

One more example to show you how you can use extensions in protocols

protocol Human {
    func walking()
    func sleeping()
}

class Men : Human {
    func walking() {
        print("Men is walking")
    }

    func sleeping() {
        print("Men is sleeping")
    }

}

extension Human {
    func eating(person : String) -> String {
        return ("\(person) is eating")
    }
}

let objMen = Men()
print(objMen.eating(person : "Men")) //Men is eating
Enter fullscreen mode Exit fullscreen mode

Here as we can see that we didn't provide eating method in protocol but is still available for class conforming to that protocol.

Hope, it helps and if you would like to add to it. Comment Below.

Top comments (0)