Level: ★☆☆ Tag: “iOS” “Swift 5.1” “Expansion” author: Muling Low review: QiShare team
Extension: To add new functionality to an existing class, structure, enumeration, or protocol type without access to the source code. Much like objective-C classification, Swift’s extension has no name. The Swift extension has the following capabilities:
- Add instance calculation properties and class calculation properties
- Define instance methods and class methods
- Provides a new initialization method
- Define the subscript
- Define and use new nested types
- Make existing types adhere to a protocol
Note: Extensions can add new functionality to a type, but cannot override existing functionality.
Extension
grammar
To declare an Extension, use the Extension keyword:
Extension SomeType {// Can add extension function}Copy the code
Extensions can extend an existing type to adopt one or more protocols.
Extension SomeType: SomeProtocol, AnotherProtocol {//Copy the code
Note: If you define an extension to add new functionality to an existing type, the new functionality is available on all existing instances of that type, even if the instance was created before the extension was defined.
Calculate attribute
Extensions can add instance calculation properties and class calculation properties. The following example adds five compute instance attributes to Swift’s built-in Double as units of distance:
extension Double {
var km: Double { returnSelf * 1_000.0} var m: Double {return self }
var cm: Double { returnSelf / 100.0} var mm: Double {self / 100.0} var mm: Double {returnSelf / 1_000.0} var Double {self / 1_000.0}returnSelf / 3.28084}}letOneInch = 25.4 mmprint("OneInch is \ oneInch meter")
// Prints "An inch is 0.0254 meters."
let threeFeet = 3.ft
print("ThreeFeet is \ threeFeet meters")
// Prints "Three feet is 0.914399970739,201 meters."
let aMarathon = 42.km + 195.m
print("Marathon Length \(aMarathon) meter")
// Prints "The marathon is 42195.0 meters long."
Copy the code
Note: Extensions can add new computed properties, but they cannot add storage properties, nor can they add attribute observers to existing properties.
Initialization method
Extensions can add initialization methods for existing types.
Extensions can also add new convenience initializers for a Class type, but cannot add new designated initializers or de-initializers for a Class type. The specified initializer or de-initializer must be implemented by the original class.
If an extension is used to add an initialization method for a value type that provides default values for all of its storage properties, and there is no custom initialization method, then we can call the default initialization method in the initialization method of the value type extension or call the initialization method generated by the member. If a custom initialization method was provided in the original implementation of a value type, its custom initialization method is called in the initialization method in the extension of that value type. Note: For a custom value type to call both default and member initializations, as well as custom initializations, the custom initialization method must be written in Extension.
If you add an initializer to the structure of another module using an extension to declare, the new initializer cannot access the self attribute until the structure calls the initializer from the module it defines.
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 () init(origi:Point,siz: size) {origin = origi size = siz} } extension Rect { init(center:Point,size:Size) {let originX = center.x - (size.width / 2)
letoriginY = center.y - (size.height / 2) self.init(origi: Point(x: originX, y: originY), siz: size) //! Init (Origin: Point(x: originX, y: originY), size: size) '}}Copy the code
methods
Extensions add instance methods and class methods to existing types.
extension Int {
func repetitions(task: () -> Void) {
for _ in0.. <self {task()}}} // Call output three times' Hello! ` 3.repetitions {print("Hello!")}Copy the code
Mutable instance methods
Value type extensions can include instance methods that use mutating modifications, allowing the instance itself to be modified.
extension Int {
mutating func square() {self = self * self}} var someInt = 3 someint.square () // someInt: 9Copy the code
The subscript
Extensions can add new subscripts to existing types.
Extension {subscript(digitIndex:Int)->Int {var baseNum = 1for _ in0.. <digitIndex { baseNum *= 10 } assert(baseNum <= self,"Integer index out of bounds.")
return (self/baseNum)%10
}
}
print(123456) [5] / / 1Copy the code
Nested types
Extensions can add new nested types to existing classes, structures, and enumerations.
extension Int {
enum Status : String,CaseIterable {
case NoAuth = "NoAuth"
case RequestError = "RequestError"
case None = "None"
}
var netStatus : String {
switch self {
case 401:
return Status.NoAuth.rawValue
case let x where x >= 500 :
return Status.RequestError.rawValue
default:
return Status.None.rawValue
}
}
}
print(401.netStatus) //! < NoAuthprint(500.netStatus) //! < RequestErrorprint(402.netStatus) //! < NoneCopy the code
Resources: Swift 5.1 official programming guide
You can add the following xiaobian wechat, and note to join the QiShare technical exchange group, xiaobian will invite you to join the QiShare technical Exchange Group.
To learn more about iOS and related new technologies, please follow our official account:
QiShare(Simple book) QiShare(digging gold) QiShare(Zhihu) QiShare(GitHub) QiShare(CocoaChina) QiShare(StackOverflow) QiShare(wechat public account)
Recommended articles: Swift 5.1 (18) – Embedded Types Swift 5.1 (17) – Type Conversion and Pattern Matching Channel usage and source code analysis and development are not cut map how to do? Vector icon (iconFont) Getting started with guide DarkMode, WKWebView, Apple login must be adapted? ATaller Strange dance weekly