An in depth explanation of static and class keywords in Swift

  • 2020-06-15 10:21:16
  • OfStack

preface

The concept of "type scope scope" in Swift has two different keywords, static and class. These two keywords do express this, but in some other languages, including ES6en-ES7en, we don't specifically address categorization/class methods and static variables/static functions. In Swift, however, the two keywords cannot be mixed.

static and class

Effect: These two keywords are used to indicate that the modified property or method is of type (class/struct/enum) and not of type instance.

static scenarios (class/struct/enum)

Modify storage properties Modify computed attributes Modifier type method

struct Point {
 let x: Double
 let y: Double
//  Modify storage properties 
 static let zero = Point(x: 0, y: 0)
//  Modify computed attributes 
 static var ones: [Point] {
  return [Point(x: 1, y: 1)]
 }
//  Modifier type method 
 static func add(p1: Point, p2: Point) -> Point {
  return Point(x: p1.x + p2.x, y: p1.y + p2.y)
 }
}

class for the scenario

Decorates class methods Modify computed attributes

class MyClass {
//  Modify computed attributes 
 class var age: Int {
  return 10
 }
//  Decorates class methods 
 class func testFunc() {
  
 }
}

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'?

Use static in protocol to modify methods or compute properties on type fields, as struct, enum, and class all support static, while struct and enum do not


protocol MyProtocol {
 static func testFunc()
}

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

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

class MyClass: MyProtocol {
 static func testFunc() {
  
 }
}

static decorates class methods that cannot be inherited; Class methods decorated 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() {
//
// }
}

The singleton


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

conclusion

static can modify the calculation attribute, storage attribute and type method of class/struct/enum. class can modify the computational properties and class methods of a class Class methods decorated by static cannot be inherited; Class methods decorated by class can be inherited Use static in protocol

reference

Swift Tips stackoverflow

Related articles: