Swift Extensions

Extensions add new functionality to an existing class, structure, or enumeration type.

Extensions can add new functionality to a type, but cannot override existing functionality.

Extensions in Swift can:

  • Add computed properties and computed static properties
  • Define instance methods and type methods
  • Provide new initializers
  • Define subscripts
  • Define and use new nested types
  • Make an existing type conform to a protocol

Syntax

Extension declarations use the keywordextension:

extension SomeType {
    // 加到SomeType的新功能写到这里
}

An extension can extend an existing type to make it conform to one or more protocols, with the syntax format as follows:

extension SomeType: SomeProtocol, AnotherProctocol {
    // 协议实现写到这里
}

Computed Properties

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

Example

The following example adds 5 computed instance properties to the Int type 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("加法运算后的值:\(addition)")
    
let subtraction = 120.sub
print("减法运算后的值:\(subtraction)")
    
let multiplication = 39.mul
print("乘法运算后的值:\(multiplication)")
    
let division = 55.div
print("除法运算后的值: \(division)")

let mix = 30.add + 34.sub
print("混合运算结果:\(mix)")

The output of the above program execution is:

加法运算后的值:103
减法运算后的值:110
乘法运算后的值:390
除法运算后的值: 11
混合运算结果:154

Initializers

Extensions can add new initializers to existing types.

This allows you to extend other types, use your own custom types as initializer parameters, or provide additional initialization options not included in the type's original implementation.

Extensions can add new convenience initializers init() to classes, but they cannot add new designated initializers or deinitializers deinit() to classes.

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:

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

Methods

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

The following example adds a new instance method named topics to the Int type:

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

4.topics({
   print("扩展模块内")       
})    
    
3.topics({
   print("内型转换模块内")       
})  

The output of the above program execution is:

Within the extension module

Thistopicsmethod uses a() -> ()single parameter of type, indicating that the function has no parameters and no return value.

After defining this extension, you can call on any integertopicsthe method, which implements the functionality of executing a task multiple times:


Mutating Instance Methods

Instance methods added through extensions can also modify the instance itself.

In structures and enumeration types, methods that modify self or its properties must mark the instance method as mutating, just as modification methods from the original implementation do.

Example

The following example adds a new mutating method named square to Swift's Double type to implement the square calculation of the original value:

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

var Trial1 = 3.3
Trial1.square()
print("圆的面积为: \(Trial1)")


var Trial2 = 5.8
Trial2.square()
print("圆的面积为: \(Trial2)")


var Trial3 = 120.3
Trial3.square()
print("圆的面积为: \(Trial3)")

The output of the above program execution is:

圆的面积为: 34.210935
圆的面积为: 105.68006
圆的面积为: 45464.070735

Subscripts

Extensions can add new subscripts to an existing type.

Example

The following example adds an integer subscript to Swift's built-in Int type. The subscript [n] returns the decimal digit

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

print(12[0])     // 输出:2
print(7869[1])   // 输出:6
print(786543[2]) // 输出:5

The output of the above program execution is:

2
6
5

Nested Types

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:

 10 
 20 
 30 
 40 
 50 
 50 
Other Extensions