Static methods are similar to static properties, anda static method , also known as a type method , is defined in Swift. Static methods are defined in the same way as static properties, where the keywords used by the enumeration and static methods of the struct are static , the keyword used by the class static method is class or static, and if the static definition is used , the method cannot be overridden in a subclass ( override); If you use the class definition, the method can be overridden by the quilt class.
static method of structure body
Look at an example of a struct static method, with the following code:
[HTML]View PlainCopyprint?
- struct Account {
- var owner: String = "Tony"//declaring instance attribute account name
- static var interestrate: Double = 0.0668//Declare static property interest rate
- static func Interestby (amount:double)-> Double {//define static method
- Return InterestRate * Amount
- }
- Func Messagewith (amount:double)-> String {//define instance method
- Let interest = Account.interestby (amount)
- Return "\ (self.owner) interest is \ (Interest)"
- }
- }
- Calling a static method
- Print (Account.interestby (10_000.00))
- var myAccount = Account ()
- Invoking instance methods
- Print (Myaccount.messagewith (10_000.00))
Enumerate static methods
Look at an example of an enumeration of static methods, with the following code:
[HTML]View PlainCopyprint?
- Enum Account {
- Case Bank of China
- Case ICBC
- Case China Construction Bank
- Case Agricultural Bank of China
- static var interestrate: Double = 0.0668//Declare static property interest rate
- static func Interestby (amount:double)-> Double {//define static method
- Return InterestRate * Amount
- }
- }
- Calling a static method
- Print (Account.interestby (10_000.00))//Call static method
As can be seen from the example, there is no difference in the use of static methods for structs and enumerations.
Class static methods
Look at an example of a class static method with the following code:
[HTML]View PlainCopyprint?
- Class Account {
- var owner: String = "Tony"//account name
- Can be replaced by static
- Class func Interestby (amount:double)-> Double {//using the keyword class to define a static method
- Return 0.08886 * Amount
- }
- }
- Calling a static method
- Print (Account.interestby (10_000.00))//Call static method
swift-static Method-Standby