SoFunction
Updated on 2025-04-11

Explanation of some basic extension functions of Swift

Existing features of classes, structures, or enum types can be added with the help of extensions. Types of functions can be added using extensions, but rewritten functions cannot use extensions.

Swift extensions:

  • Add computed attributes and calculate type attributes
  • Methods for defining instances and types
  • New initialization provided
  • Define subscript
  • Define and use new nested types
  • Make existing types consistent with protocols

Extension statement with keyword extension

grammar

Copy the codeThe code is as follows:

extension SomeType {
   // new functionality can be added here
}
Existing types can also be added with extensions to make them a protocol standard and their syntax similar to classes or structures.

extension SomeType: SomeProtocol, AnotherProtocol {
   // protocol requirements is described here
}


Calculate properties
Computing the "Instance" and "Type" properties can also be extended with the help of extensions.
Copy the codeThe code is as follows:

extension Int {
   var add: Int {return self + 100 }
   var sub: Int { return self - 10 }
   var mul: Int { return self * 10 }
   var div: Int { return self / 5 }
}
   
let addition =
println("Addition is \(addition)")
   
let subtraction =
println("Subtraction is \(subtraction)")
   
let multiplication =
println("Multiplication is \(multiplication)")
   
let division =
println("Division is \(division)")

let mix = +
println("Mixed Type is \(mix)")


When we run the above program using playground, we get the following results.
Addition is 103
Subtraction is 110
Multiplication is 390
Division is 11
Mixed Type is 154

Initializer
Swift has the flexibility to add new initialization to existing types by extending new initializations. Users can add their own custom types to extend the defined types, and additional initialization options are also OK. Extensions only support init(). deinit() is not supported by extensions.

Copy the codeThe code is as follows:

struct sum {
   var num1 = 100, num2 = 200
}
  
struct diff {
   var no1 = 200, no2 = 100
}
  
struct mult {
   var a = sum()
   var b = diff()
}
  
let calc = mult()
println ("Inside mult block \(.num1, .num2)")
println("Inside mult block \(.no1, .no2)")
  
let memcalc = mult(a: sum(num1: 300, num2: 500),b: diff(no1: 300, no2: 100))
 
println("Inside mult block \(.num1, .num2)")
println("Inside mult block \(.no1, .no2)")
  
extension mult {
   init(x: sum, y: diff) {
      let X = x.num1 + x.num2
      let Y = y.no1 + y.no2
   }
}
  

let a = sum(num1: 100, num2: 200)
println("Inside Sum Block:\( a.num1, a.num2)")
  
  
let b = diff(no1: 200, no2: 100)
println("Inside Diff Block: \(b.no1, b.no2)")


When we run the above program using playground, we get the following results.
Inside mult block (100, 200)
Inside mult block (200, 100)
Inside mult block (300, 500)
Inside mult block (300, 100)
Inside Sum Block:(100, 200)
Inside Diff Block: (200, 100)

method
New instance methods and types of methods can be further added to subclasses with the help of extensions.

Copy the codeThe code is as follows:

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

({
   println("Inside Extensions Block")      
})   
   
({
   println("Inside Type Casting Block")      
}) 


When we run the above program using playground, we get the following results.
Inside Extensions Block
Inside Extensions Block
Inside Extensions Block
Inside Extensions Block
Inside Type Casting Block
Inside Type Casting Block
Inside Type Casting Block

topics() function uses a type whose argument is (summation: () -> ()) to indicate that the function does not take any arguments and it does not return any value. The function is called many times, the block is initialized, and the topic() method is initialized.

Different example methods deformation
Example methods can also be used as a deformation of the extension declaration.

The method that modifies its own structure and counting or its properties must be marked with the example method deformation, just like a method that implements deformation from an original method.

Copy the codeThe code is as follows:

extension Double {
   mutating func square() {
      let pi = 3.1415
      self = pi * self * self
   }
}

var Trial1 = 3.3
()
println("Area of circle is: \(Trial1)")


var Trial2 = 5.8
()
println("Area of circle is: \(Trial2)")


var Trial3 = 120.3
()
println("Area of circle is: \(Trial3)")


When we run the above program using playground, we get the following results.
Area of circle is: 34.210935
Area of circle is: 105.68006
Area of circle is: 45464.070735

Subscript
Adding new flags declared instances can also be extended.

Copy the codeThe code is as follows:

extension Int {
   subscript(var multtable: Int) -> Int {
      var no1 = 1
      while multtable > 0 {
         no1 *= 10
         --multtable
      }
      return (self / no1) % 10
   }
}
   
println(12[0])
println(7869[1])
println(786543[2])

When we run the above program using playground, we get the following results.
2
6
5

Nested Types
Nested types are classes, structures, and enumeration instances, and can also be extended with the help of extensions.

Copy the codeThe code is as follows:

 extension Int {
   enum calc
   {
      case add
      case sub
      case mult
      case div
      case anything
   }

   var print: calc {
      switch self
      {
         case 0:
            return .add
         case 1:
            return .sub
         case 2:
            return .mult
         case 3:
            return .div
         default:
            return .anything
       }
   }
}

func result(numb: [Int]) {
   for i in numb {
      switch {
         case .add:
            println(" 10 ")
          case .sub:
            println(" 20 ")
         case .mult:
         println(" 30 ")
         case .div:
         println(" 40 ")
         default:
         println(" 50 ")

      }
   }
}

result([0, 1, 2, 3, 4, 7])


When we run the above program using playground, we get the following results.
10 
20 
30 
40 
50 
50