The static and the class

Both keywords are used to indicate that the property or method being modified is a type (class/struct/enum), not an instance of the type.

Static Applied scenario (class/struct/enum)

  • Modify storage properties
  • Modified computed properties
  • Modifying type methods
struct Point {
    let x: Double
    letY: Double // modifies the storage property staticletZero = Point(x: 0, y: 0) static var ones: [Point] {returnStatic func add(p1: Point, p2: Point) -> Point {static func add(p1: Point, p2: Point) -> Point {return Point(x: p1.x + p2.x, y: p1.y + p2.y)
    }
}
Copy the code

Class applies to scenarios

  • Modifying class methods
  • Modified computed properties
Class var age: Int {class var age: Int {return} // modify the class method class functestFunc() {}}Copy the code

Matters needing attention

  • 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'?
Copy the code
  • Used in protocolstaticTo modify a method or compute property on a type field
protocol MyProtocol {
    static func testFunc()
}

struct MyStruct: MyProtocol {
    static func testFunc() {
        
    }
}

enum MyEnum: MyProtocol {
    static func testFunc() {
        
    }
}

class MyClass: MyProtocol {
    static func testFunc() {}}Copy the code
  • Static modified class methods cannot be inherited; Class methods 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() {// //}}Copy the code

The singleton

class SingleClass {
    static let shared = SingleClass()
    private init() {}}Copy the code

conclusion

  • The static can modifyclass/struct/enumCalculation properties, storage properties, type methods of; Class can modify the computed properties and class methods of a class
  • Static modified class methods cannot be inherited; Class methods can be inherited
  • Static is used in protocol

reference

  • Swift Tips
  • stackoverflow