Swift extension


Release date:2023-12-06 Update date:2023-12-08 Editor:admin View counts:271

Label:

Swift extension

An extension is to add new functionality to an existing class, structure, orenumerated type.

An extension can add new functionality to a type, but it cannot override existing functionality.

The extensions in Swift can:

  • Add computational attributes and computational static attributes

  • Define instance methods and type methods

  • Provide new constructors

  • Define subscript

  • Define and use new nested types

  • Make an existing type conform to a protocol

Grammar

Extension declaration uses keywords extension :

extension SomeType {
    // The new features added to SomeType are written here
}

An extension can extend an existing type to adapt to one or more protocols in the following syntax format:

extension SomeType: SomeProtocol, AnotherProctocol {
    // The protocol implementation is written here
}

Computational attribute

Extensions can add computational instance properties and computational type properties to existing types.

Example

The following example reports to the Int type adds five computational instance properties and extends its functionality:

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 = 3.add
print("Value after addition operation:\(addition)")

let subtraction = 120.sub
print("The value after subtraction operation:\(subtraction)")

let multiplication = 39.mul
print("The value after multiplication operation:\(multiplication)")

let division = 55.div
print("Value after division operation: \(division)")

let mix = 30.add + 34.sub
print("Mixed operation result:\(mix)")

The output of the above program execution is as follows:

Value after addition operation: 103
Value after subtraction: 110
Value after multiplication: 390
Value after division: 11
Mixed operation result: 154

Constructor

Extensions can add new constructors to existing types.

This allows you to extend other types, take your own custom type as constructor parameters, or provide additional initialization options that are not included in the original implementation of that type.

Extensions can add new convenience constructors to the class init() , butthey cannot add a new specified constructor or destructor to the class deinit() .

struct sum {
    var num1 = 100, num2 = 200
}

struct diff {
    var no1 = 200, no2 = 100
}

struct mult {
    var a = sum()
    var b = diff()
}


extension mult {
    init(x: sum, y: diff) {
        _ = x.num1 + x.num2
        _ = y.no1 + y.no2
    }
}


let a = sum(num1: 100, num2: 200)
let b = diff(no1: 200, no2: 100)

let getMult = mult(x: a, y: b)
print("getMult sum\(getMult.a.num1, getMult.a.num2)")
print("getMult diff\(getMult.b.no1, getMult.b.no2)")

The output of the above program execution is as follows:

getMult sum(100, 200)
getMult diff(200, 100)

Method

Extensions can add new instance methods and type methods to existing types.

The following example reports to the Int type to add a file named topics the new instance method of

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

4.topics({
   print("Within the expansion module")
})

3.topics({
   print("Internal conversion module")
})

The output of the above program execution is as follows:

Within the expansion module
Within the expansion module
Within the expansion module
Within the expansion module
Internal conversion module
Internal conversion module
Internal conversion module

This topics Method uses a () -> () type, indicating that the function has no arguments and no return value.

Once the extension is defined, you can call the topics method, the function is to perform a task multiple times

Variable instance method

The instance itself can also be modified by extending the added instance method.

Modification in structures and enumeration types self or its propertiesmust mark the instance method as mutating , just like the modification method from the original implementation

Example

The following example reports to the Swift of Double type has beenadded with a new name square to realize the square calculation of an original value

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

var Trial1 = 3.3
Trial1.square()
print("The area of a circle is: \(Trial1)")


var Trial2 = 5.8
Trial2.square()
print("The area of a circle is: \(Trial2)")


var Trial3 = 120.3
Trial3.square()
print("The area of a circle is: \(Trial3)")

The output of the above program execution is as follows:

The area of the circle is 34.210935
The area of the circle is: 105.68006
The area of the circle is: 45464.070735

Subscript

An extension can add a new subscript to an existing type.

Example

The following example gives a built-in type to Swift Int an integer subscript was added. The subscript [n] returns a decimal number

extension Int {
   subscript(var multtable: Int) -> Int {
      var no1 = 1
      while multtable > 0 {
         no1 *= 10
         --multtable
      }
      return (self / no1) % 10
   }
}

print(12[0])
print(7869[1])
print(786543[2])

The output of the above program execution is as follows:

2
6
5

Nesting type

Extensions can add new nested types to existing classes, structures, and enumerations:

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 i.print {
         case .add:
            print(" 10 ")
          case .sub:
            print(" 20 ")
         case .mult:
         print(" 30 ")
         case .div:
         print(" 40 ")
         default:
         print(" 50 ")

      }
   }
}

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

The output of the above program execution is as follows:

10
20
30
40
50
50

Powered by TorCMS (https://github.com/bukun/TorCMS).