Extensions

作者: 宋奕Ekis | 来源:发表于2021-08-24 10:50 被阅读0次

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..<self {
            task()
        }
    }
}

3.repetitions {
    print("Hello!")
}
// Hello!
// Hello!
// Hello!

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

    本文链接:https://www.haomeiwen.com/subject/dyhdiltx.html