Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Syntax of extensions
3.
Computed Properties
4.
Initializers
5.
Methods
6.
Mutating Instance Methods
7.
Subscripts
8.
Nested Types
9.
Frequently Asked Questions
9.1.
When should I use deinit() in swift?
9.2.
When are protocol extensions useful in Swift?
9.3.
What is init() in Swift?
9.4.
Why does Swift need protocols?
10.
Conclusion
Last Updated: Mar 27, 2024
Easy

Swift extensions

Author SAURABH ANAND
0 upvote

Introduction

In this article, we will learn everything there is to know about Swift extensions, including its properties, syntax, methods, and nested extensions.

Extensions provide an existing class, structure, enumeration, or protocol type new capability.

Now let's see the syntax of Swift extensions.

Syntax of extensions

The keyword 'extension' is used to declare extensions.

extension Some_Type {
// new extension functionality can be added here
}

 

Existing types can also be extended to become protocol standards, and their syntax is comparable to that of classes or structures.

extension Some_Type: Some_Protocol, Another_Protocol {
// protocol requirements is described here
}

Computed Properties

Extensions can also be used to extend computed 'instance' and 'type' properties.

extension Int {
 var addn: Int { return self + 10 }
 var subn: Int { return self - 100 }
 var muln: Int { return self * 150 }
 var divn: Int { return self / 55 }
}

let add = 3.addn
print("Addition is \(add)")

let sub = 120.subn
print("Subtraction is \(sub)")

let mul = 39.muln
print("Multiplication is \(mul)")

let div = 55.divn
print("Division is \(div)")

let mix_them = 30.addn + 34.subn
print("Mixed Type is \(mix_them)")

 

Output:

Addition is 13
Subtraction is 20
Multiplication is 5850
Division is 1
Mixed Type is -26

Initializers

Extensions in Swift 4 make it possible to add new initializers to an existing type. The user can add their own custom types to extend the types already provided, and other initialization options are also available. Only init is supported by extensions (). The extensions do not support deinit()

// class declearation
class  stick {
  var length: Double

  // initialize property
  init() {
    length = 5.5
    print("Creating a stick.")
    print("Length = ", length)
  }
}

// create an object
var stick1 = stick()

 

Output:

Creating a stick.
Length =  5.5

Methods

With the use of extensions, new instance methods and type methods can be introduced to the subclass.

extension Int {
  func topic(summation: () -> ()) {
     for _ in 0..<self {
        summation()
     }
  }
}

4.topic(summation: {
  print("Inside Extn Block")
})

3.topic(summation: {
  print("Inside TypeCast Block")
})

 

Output:

Inside Extn Block
Inside Extn Block
Inside Extn Block
Inside Extn Block
Inside TypeCast Block
Inside TypeCast Block
Inside TypeCast Block

 

The topic() function takes an argument of type '(summation: () -> ()' to indicate that it takes no arguments and returns no values. To call that procedure several times, the block is initialised, as well as the call to the method with topic().

Mutating Instance Methods

When defined as extensions, instance methods can also be altered. Structure and enumeration methods that affect self or its properties must indicate the instance method as mutating, much like original implementation modifying methods.

extension Double {
 mutating func sq() {
     let pi = 3.1415;
     self = pi * self * self
 }
}
var Try1 = 3.3
Try1.sq()
print("Area of circle is: \(Try1)")
var Try2 = 5.8
Try2.sq()
print("Area of circle is: \(Try2)")
var Try3 = 120.3
Try3.sq()
print("Area of circle is: \(Try3)")

 

Output:

Area of circle is: 34.21093499999999
Area of circle is: 105.68006
Area of circle is: 45464.070735

Subscripts

Extensions can also be used to add new subscripts to already declared instances.

extension Int {
    subscript(digit: Int) -> Int {
        var deciBase = 1
        for _ in 0..<digit {
            deciBase *= 10
        }
        return (self / deciBase) % 10
    }
}
print(746381295[0])

print(746381295[1])

print(746381295[2])

print(746381295[8])

 

Output:

5
9
2
7

Nested Types

Extensions can be used to expand nested types for class, structure, and enumeration instances

extension Int {
 enum calculate {
     case addn
     case subn
     case multn
     case divn
     case any
 }
 var print: calculate {
     switch self {
       case 0:
           return .addn
       case 1:
           return .subn
       case 2:
           return .multn
       case 3:
           return .divn
       default:
           return .any
     }
 }
}
func result(number: [Int]) {
 for i in number {
     switch i.print {
       case .addn:
           print(" 10 ")
       case .subn:
           print(" 20 ")
       case .multn:
           print(" 30 ")
       case .divn:
           print(" 40 ")
       default:
           print(" 50 ")
     }
 }
}
result(number: [0,1,2,3,4,7])

 

Output:

10
20
30
40
50
50

Frequently Asked Questions

When should I use deinit() in swift?

That method isn't needed, however, you can use it if you need to do some action or cleaning before disposing of the object.

When are protocol extensions useful in Swift?

Swift is sometimes referred to be a "protocol-oriented programming language" because protocol extensions are utilized everywhere. We utilize them to add functionality to protocols directly, eliminating the need to duplicate functionality across several structs and classes.

What is init() in Swift?

The process of preparing an instance of an enumeration, structure, or class for use is known as initialization.

Why does Swift need protocols?

Protocols allow us to describe how structs, classes, and enums should work, including what methods and properties they should have. Swift will enforce these rules for us, ensuring that when we claim a type conforms to a protocol, it contains all of the methods and characteristics that the protocol requires.

Conclusion

In this article, we have extensively discussed the concept of Swift extensions. We started with the introduction of Swift extensions, the syntax of swift extensions, computed properties of Swift extensions, initializers, and methods, and finally concluded with nested type Swift extensions. 

After reading about the swift extensions, are you not feeling excited to read/explore more articles on the topic of swift? Don't worry; Coding Ninjas has you covered. To learn, see  Swift continue and fallthrough statements, Swift Basic Syntax and first program, and Swift Access Control.

Refer to our Guided Path on Coding Ninjas Studio to upskill yourself in Data Structures and AlgorithmsCompetitive ProgrammingJavaScriptSystem Design, and many more! If you want to test your competency in coding, you may check out the mock test series and participate in the contests hosted on Coding Ninjas Studio! But if you have just started your learning process and are looking for questions asked by tech giants like Amazon, Microsoft, Uber, etc; you must look at the problems, interview experiences, and interview bundle for placement preparations.

Nevertheless, you may consider our paid courses to give your career an edge over others!

Do upvote our blogs if you find them helpful and engaging!

Happy Learning!

Live masterclass