Swift Extensions Example

1. Introduction

Extensions in Swift allow you to add new functionality to an existing class, structure, enumeration, or protocol type. This includes the ability to extend types for which you don’t have access to the original source code. Extensions are similar to categories in Objective-C. However, Swift extensions don't have names. With extensions, you can add computed properties, instance methods, type methods, initializers, and even provide new conformances to protocols.

2. Source Code Example

// Original Int type
// Int is a built-in data type in Swift and here we will add new functionality using an extension

extension Int {
    // Computed property to check if a number is even
    var isEven: Bool {
        return self % 2 == 0
    }

    // Instance method to add a value to the current integer
    func add(value: Int) -> Int {
        return self + value
    }
}

let number = 4
if number.isEven {
    print("\(number) is even.")
} else {
    print("\(number) is odd.")
}

print("\(number) + 5 = \(number.add(value: 5))")

Output:

4 is even.
4 + 5 = 9

3. Step By Step Explanation

1. We begin by defining an extension for the Int type, which is a built-in type in Swift. This extension adds new functionality to every integer value.

2. The isEven computed property is added to the Int type to check if an integer is even. It returns true if the number is even, and false otherwise.

3. The add(value:) instance method is another addition, which lets us add a specified value to the current integer.

4. We then create an integer variable named number with a value of 4.

5. Using the newly extended functionality, we can check if number is even and also add a value (5 in this case) to it using the add(value:) method.


Comments