Preface
Swift represents "type scope scope" The concept has two different keywords, namely static and class. Both keywords do express this meaning, but in some other languages, including Objective-C, we do not specifically distinguish categorical variables/class methods and static variables/static functions. However, in Swift, these two keywords cannot be mixed.
Static and class
Function: These two keywords are used to indicate that the modified attribute or method is of type (class/struct/enum), not of type instances.
static applicable scenarios (class/struct/enum)
- Modify storage properties
- Modify the calculation attributes
- Modification type method
struct Point { let x: Double let y: Double // Modify storage attributes static let zero = Point(x: 0, y: 0) // Modify the calculation attributes static var ones: [Point] { return [Point(x: 1, y: 1)] } // Modify type method static func add(p1: Point, p2: Point) -> Point { return Point(x: + , y: + ) } }
Class Applicable Scenarios
- Modification method
- Modify the calculation attributes
class MyClass { // Modify the calculation attributes class var age: Int { return 10 } // Modify class method class func testFunc() { } }
Things to note
class cannot modify the storage properties of a class, static can modify the storage properties of a class
//class let name = "jack" error: Class stored properties not supported in classes; did you mean 'static'?
Use static in protocol to modify methods or computed properties on type domains, because struct, enum, and class all support static, while struct and enum do not support class
protocol MyProtocol { static func testFunc() } struct MyStruct: MyProtocol { static func testFunc() { } } enum MyEnum: MyProtocol { static func testFunc() { } } class MyClass: MyProtocol { static func testFunc() { } }
Class methods modified by static cannot be inherited; class methods modified by class can be inherited
class MyClass { class func testFunc() { } static func testFunc1() { } } class MySubClass: MyClass { override class func testFunc() { } // error: Cannot override static method // override static func testFunc1() { // // } }
Single case
class SingleClass { static let shared = SingleClass() private init() {} }
Summarize
- static can modify the calculation properties, storage properties, and type methods of class/struct/enum; class can modify the calculation properties and class methods of class
- Class methods modified by static cannot be inherited; class methods modified by class can be inherited
- To use static in protocol
refer to
- Swift Tips
- *
OK, the above is the entire content of this article. I hope that the content of this article has certain reference value for everyone's study or work. Thank you for your support.