Protocol extensions in swift

Time:2021-12-31
  • extension
  1. Extensions add new functionality to existing classes, structs, enumeration types, or protocols. This also includes the ability to extend types for source code without access (so-called reverse modeling)
  2. The extension is similar to the category in Objective-C. (different from the classification of Objective-C, Swift’s extension has no name)
  • Extension capability
  1. Add calculation instance properties and calculation type properties
  2. Define instance methods and type methods
  3. Provide a new initializer
  4. Define subscript
  5. Define and use new infill types
  6. Make an existing type conform to a protocol
  7. Extensions can add new methods to a type, but they cannot override existing methods
  • Calculation properties
  1. Extension can add calculation instance properties and calculation type properties to existing types
extension Double {
    var km: Double { return self * 1_000.0 }
    var m: Double { return self }
    var cm: Double { return self / 100.0 }
    var mm: Double { return self / 1_000.0 }
    var ft: Double { return self / 3.28084 }
}

let oneInch = 25.4.mm
print("One inch is \(oneInch) meters")
let threeFeet = 3.ft
print("Three feet is \(threeFeet) meters")
  • Initializer
  1. Extensions can add new initializers to existing types. This allows you to extend other types, have the initializer accept your custom type seat form parameters, or provide additional initialization options not included in the original implementation of the type
  2. An extension can add a new convenient initializer for a class, but it cannot add a specified initializer or de initializer for a class. Specifies that initializers and de initializers must be provided by the implementation of the original class
struct Size {
    var width   = 0.0
    var height  = 0.0
}
struct Point {
    var x = 0.0
    var y = 0.0
}
struct Rect {
    var origin  = Point()
    var size    = Size()
}

extension Rect {
    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.0, y: 4.0), size: Size(width: 3.0, height: 3.0))
  • method
  1. Extensions can add new instance methods and type methods to existing types
extension Int {
    func repetitions(task: () -> Void) {
        for _ in 0..<self {
            task()
        }
    }
}
3.repetitions {
    print("Hello!")
}
  • Mutating method
  1. The extended instance method can modify (or mutate) the instance itself. Structure and enumeration type methods must mark the instance method as mutating when modifying self or its own attributes, which is the same as the original variant method
extension Int {
    mutating func square() {
        self = self * self
    }
}
var someInt = 3
someInt.square()
print(someInt)
  • subscript
  1. Extensions can add new subscripts to existing types
extension Int {
    subscript(digitIndex: Int) -> Int {
        var decimalBase = 1
        for _ in 0..<digitIndex {
            decimalBase *= 10
        }
        return (self / decimalBase) % 10
    }
}
746381295[0]
746381295[1]
746381295[2]
746381295[5]
  • Add an inline type.
  1. Extensions can add new embedded types to existing classes, structs, and enumeration types
extension Int {
    enum Kind {
        case negative, zero, positive
    }
    var kind: Kind {
        switch self {
        case 0:
            return .zero
        case let x where x > 0 :
            return .positive
        default:
            return .negative
        }
    } 
}

Recommended Today

Could not get a resource from the pool when the springboot project starts redis; nested exception is io. lettuce. core.

resolvent: Find your redis installation path: Start redis server Exe After successful startup: Restart project resolution. ———————————————————————->Here’s the point:<——————————————————————- Here, if you close the redis command window, the project console will report an error. If you restart the project, the same error will be reported at the beginning, The reason is: It is inconvenient to […]