You can add new features to a class
UIViewController
UIViewController { // 为 UIViewController 添加的新功能写到这里}
Double
Extension Double {varkm:double {return Self * 1_000. 0}varm:double {return Self}varcm:double {return Self / 100.0}varmm:double {return Self / 1_000. 0}var ft: Double {return Self / 3.28084}varsq:double {return Self * Self}}
ViewController
Custom
extension ViewController{ printfChars() { print("I am char") }}
Two-variable instance method (mutating Instance Methods)
An instance method that is added by extension can also modify the instance itself. A method that modifies self or its properties in a struct and enumeration type must label the instance method as mutating, just as a mutable method from the original implementation.
The following example adds a variable method named Square to the Int type of Swift to calculate the square value of the original value:
改变Int 值本身
Int { mutating func square() { selfselfself }}
Three nested types (Nested Types)
Extensions can add new nested types for existing classes, structs, and enumerations:
extension Int { enum Kind { case Negative, Zero, Positive } var kind: Kind { switch self { case0: return .Zero caseletwhere0: return .Positive default: return .Negative } }}
In Viewcontroller
In Viewdidload
Self. Printfchars () Let Oneinch =25.4. mmPrint("one inch is \ (oneinch) meters")//One inch is 0.0254 metersLet Dou =23.4. sqPrint("\ (Dou)")//547.56Let numbers = [1,2,4,5,6,3,0,- Wu,- $] Self. Printintegerkinds (Numbers)//+ + + + + + 0--varIntnumb =5Intnumb.square ()Print("\ (intnumb)")///
This example Int
adds a nested enumeration. This named Kind
enumeration represents the type of a particular integer. Specifically, it means that integers are positive, 0, or negative.
This example also Int
adds a computed instance property, that is, to Kind
return the appropriate enumeration member based on an integer Kind
.
Now, this nested enumeration can be used with any Int
value:
Func Printintegerkinds (numbers: [Int]) { forNumberinchNumbers {SwitchNumber.kind { Case.Negative:Print("- ",Terminator:"") Case.Zero:Print("0",Terminator:"") Case.Positive:Print("+ ",Terminator:"") } }Print("") }
Swift extension (Extensions) (14)