Swift中static和class关键字的深入讲解

2020-01-09 00:11:44于海丽

class不能修饰类的存储属性,static可以修饰类的存储属性


//class let name = "jack" error: Class stored properties not supported in classes; did you mean 'static'?

在protocol中使用static来修饰类型域上的方法或者计算属性,因为struct、enum、class都支持static,而struct和enum不支持class


protocol MyProtocol {
 static func testFunc()
}

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

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

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

static修饰的类方法不能继承;class修饰的类方法可以继承


class MyClass {
 class func testFunc() {
  
 }
 
 static func testFunc1() {
  
 }
}

class MySubClass: MyClass {
 override class func testFunc() {
  
 }
 
// error: Cannot override static method
// override static func testFunc1() {
//
// }
}

单例


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

总结

  • static能修饰class/struct/enum的计算属性、存储属性、类型方法;class能修饰类的计算属性和类方法
  • static修饰的类方法不能继承;class修饰的类方法可以继承
  • 在protocol中要使用static

    参考