当前位置:网站首页>Swift extension

Swift extension

2022-06-09 05:27:00 same_ life

Extended concept

  • Extension is to extend an existing class 、 Structure 、 Enumeration type 、 Or protocol to add new features .
  • Extensions can add new functionality to a type , But you can't rewrite existing functions .
  • Extension and Objective-C Medium category similar .( And Objective-C The different classification is ,Swift No extension for word .)

Extended functionality

  • Add calculation instance properties and calculation type properties
  • Define instance methods and type methods
  • Provide a new initializer
  • Define subscripts
  • Define and use new inline types
  • Make existing types conform to a protocol
  • Extensions can add new methods to a type , But you can't override existing methods

Extended syntax

  • Declare that the extension uses extension keyword
extension SomeType {
    
    //  Need to expand  SomeType  New functions 
}
  • An extension can extend an existing type , Enable it to adapt to one or more protocols , The syntax is as follows :
extension SomeType: SomeProtocol, AnotherProtocol {
    
    //  Protocol implementation 
}

Compute properties

  • Extensions can add calculation instance properties and calculation type properties to existing types .
// towards  Double  Type added  4  Compute instance properties and extend their functions 
extension Double {
    
    var km: Double {
     return self * 1000.0 }
    var m: Double {
     return self }
    var cm: Double {
     return self / 100.0 }
    var mm: Double {
    return self / 10000.0 }
}
let num1 = 1.2.km
print("num1 is \(num1) meters")
let num2 = 250.cm
print("num2 is \(num2) meters")

The initializer

  • Extensions can add new initializers to existing types . This allows you to extend other types so that the initializer receives your custom type as a formal parameter , Or provide additional initialization options not included in the original implementation of the type .
  • Extension can add new convenient initializers to classes , However, you cannot add a specified initializer or de initializer to a class . Specify initializer And de initializer Must be provided by the implementation of the original class .
struct Size {
    
    var width = 0.0, height = 0.0
}
struct Point {
    
    var x = 0.0, y = 0.0
}
struct Rect {
    
    var origin = Point()
    var size = Size()
}
extension Rect {
      // Add a new initializer to an existing type 
    init(center: Point, size: Size) {
    
        let originX = center.x - (size.width / 2)
        let originY = center.y - (size.height / 2)
        self.init(origin: Point(x: originX, y: originY), size: size)
    }
}
let centerRect = Rect(center: Point(x: 4, y: 4), size: Size(width: 3, height: 3))

Method

  • Extensions can add new instance methods and type methods to existing types .
// Add extensions to instance methods 
extension Int {
    
    func repititions(task: () -> Void) {
    
        for _ in 0..<self {
    
            task()
        }
    }
}
3.repititions {
    
    print("hello")
}
/**  Print : hello hello hello */

mutating Method

  • The extended instance method can still be modified ( Or change ) The instance itself . Structure and enumeration type methods are being modified self Or its own properties, the instance method must be marked as mutating , It's the same as the variation method originally implemented .
// Mutation method 
extension Int {
    
    mutating func square() {
    
        self = self * self
    }
}
var someInt = 3
someInt.square()
print(someInt) // 9

Subscript

  • Extensions can add new subscripts to existing types .
extension Int {
    
    subscript(digitalIndex: Int) -> Int {
    
        var decimalBase = 1
        for _ in 0..<digitalIndex {
    
            decimalBase *= 10
        }
        return (self / decimalBase) % 10
    }
}
746381295[0]   // 5
746381295[1]   // 9
746381295[2]   // 2
746381295[8]   // 7

Add inline type

  • The extension can be an existing class 、 Structure and enum types add new inline types .
extension Int {
    
    enum Kind {
    
        case negative, zero, pozitive
    }
    var kind: Kind {
    
        switch self {
    
        case 0:
            return .zero
        case let x where x > 0:
            return .pozitive
        default:
            return .negative
        }
    }
}
print(3.kind)   // pozitive
原网站

版权声明
本文为[same_ life]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/160/202206090521444778.html