Extending Classes in Swift. Class extension.

The below code example in Swift demonstrates how you can extend classes in Swift.

Extending Class in Swift

As an example, let’s learn how we can extend class Int. 

Create a new Swift file in your current project and add there the following extension with a function that substructs a value.

extension Int {
    func takeAway(value: Int) -> Int {
        return self-value
    }
}

You can then use the above extension on any Int in your project the following way:

let a = 10
let b = a.takeAway(value: 3)

print(b)

The output of the above code is on the image below:

Extend class in swift. Code example.
Extend class in swift. Code example.

Extending Custom Classes in Swift

You can use an extension to extend any other custom classes you create in Swift. Let’s consider the following custom class.

class Person {
    var firstName: String
    var lastName: String
    
    init(firstName: String, lastName: String) {
        self.firstName = firstName
        self.lastName = lastName
    }
}

You can extend the above class by adding one more property called to create Person’s full name like so:

extension Person {
    var fullName: String {
        return firstName + " " + lastName
    }
}

Now you can instantiate an instance of Person class and print the value of fullName:

let person = Person(firstName: "Sergey", lastName: "Kargopolov")

print(person.fullName)

 


Leave a Reply

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

Free Video Lessons

Enter your email and stay on top of things,

Subscribe!