Extensions

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

Extensions in Swift can:

  • Add computed instance properties and computed type 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

but they can’t override existing functionality.

Extension Syntax

extension SomeType: SomeProtocol, AnotherProtocol {
    // implementation of protocol requirements goes here
}

Extension has extensive scene we can image, just like this:

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")
// Prints "One inch is 0.0254 meters"
let threeFeet = 3.ft
print("Three feet is \(threeFeet) meters")
// Prints "Three feet is 0.914399970739201 meters"

even this:

extension Int {
    func repetitions(task: () -> Void) {
        for _ in 0..

Honestly, I am started it can be used in this way.

It can extend the class we don't have access to the origianal code!!!

Let’t think!

你可能感兴趣的:(Extensions)