Swift Extension summary, swiftextension
Summary
Extended functions are added to existing classes, structures, enumeration, and protocols. Similar to the Category in Objective-C, the Extension has no name. Extensions can do the following:
- Add computing instance attributes and computing type attributes
- Define instance methods and types
- Provide new Initiators
- Define subscript
- Define and use new built-in types
- Make an existing type obey a protocol
Note: New functions can be added for extensions, but existing functions cannot be overwritten.
Extended syntax
Use the extension keyword, as shown below.
extension SomeType{ //new functionality to add to SomeType goes here}extension SomeType: SomeProtocol, AnotherProtocol{ //implementation of protocol requirements goes here}
Note: If you have extended new functions for existing types, no matter when you expand them, even if you extend them after the instance is defined, all instances of this type can use this new function,
Calculation attribute
The extension can add computing instance attributes and computing type attributes to existing types, as shown in the following extension of the Double type:
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 / 1000.0 } var ft: Double { return self / 3.28084 }}let oneInch = 25.4.mm;print("One inch is \(oneInch)meters")
Constructor (Initializers)
A type can be extended to implement custom constructor, but only Convenience Initializers can be added. The specified Constructor (Designated Initializers) cannot be added ).
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()}
Rect
Struct does not have a custom constructor. Because its attributes have initial values, the system provides a default constructor and one-by-one member constructor. When a constructor is added, you can call the one-by-one member constructor. Make sure that all storage properties of the type have initial values.
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) }}
Method
You can add the instance method and type method as follows.
Extension Int {funcrepetitions (task: ()-> Void) {for _ in 0 .. <self {task () }}4. repetitions {// print ("hello ")}
Mutating Instance Methods)
You can modify the instance itself by extending the added instance method. Methods In struct and enumeration types must be used to modify the instance itself or attributes.mutating
To modify the method, so the extension method also needs to be addedmutating
.
extension Int{ mutating func square() { self = self * self print(self) }}var someInt = 3someInt.square()
Subscript
Extension can add a new subscript to an existing type, as shown in the following example:
extension Int{ subscript(digitIndex: Int) -> Int { var decimalBase = 1 for _ in 0..<digitIndex { decimalBase *= 10 } return(self/ decimalBase) % 10 }}746381295[0] // returns 5746381295[1] // returns 9746381295[2] // returns 2746381295[8] // returns 7
Built-in type
Extensions can add new built-in types to existing classes, struct, and enumeration types.
extension Int{ enumKind { casenegative, zero, positive } var kind: Kind { switch self { case 0: return .zero case let x where x > 0: return .positive default: return .negative } }}func printIntegerKinds(_numbers: [Int]) { for number in numbers { switch number.kind { case .negative: print("-", terminator: "") case .zero: print("0", terminator: "") case .positive: print("+", terminator: "") } } print("")}printIntegerKinds([3, 19, -27, 0, -6, 0, 7])// Prints "+ + - 0 - 0 +
Author: Chen Ge
Link: https://www.jianshu.com/p/edf4cad8dfd5
Source: Simplified book
Copyright belongs to the author. For commercial reprint, please contact the author for authorization. For non-commercial reprint, please indicate the source.