深入理解Swift中static和class关键字

栏目: Swift · 发布时间: 6年前

内容简介:作用:这两个关键字都是用来说明被修饰的属性或者方法是类型(class/struct/enum)的,而不是类型实例的。

作用:这两个关键字都是用来说明被修饰的属性或者方法是类型(class/struct/enum)的,而不是类型实例的。

static 适用的场景(class/struct/enum)

  • 修饰存储属性
  • 修饰计算属性
  • 修饰类型方法
struct Point {
    let x: Double
    let y: Double
//    修饰存储属性
    static let zero = Point(x: 0, y: 0)
//    修饰计算属性
    static var ones: [Point] {
        return [Point(x: 1, y: 1)]
    }
//    修饰类型方法
    static func add(p1: Point, p2: Point) -> Point {
        return Point(x: p1.x + p2.x, y: p1.y + p2.y)
    }
}
复制代码

class 适用的场景

  • 修饰类方法
  • 修饰计算属性
class MyClass {
//    修饰计算属性
    class var age: Int {
        return 10
    }
//    修饰类方法
    class func testFunc() {
        
    }
}
复制代码

注意事项

  • 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() {}
}
复制代码

以上所述就是小编给大家介绍的《深入理解Swift中static和class关键字》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Nine Algorithms That Changed the Future

Nine Algorithms That Changed the Future

John MacCormick / Princeton University Press / 2011-12-27 / GBP 19.95

Every day, we use our computers to perform remarkable feats. A simple web search picks out a handful of relevant needles from the world's biggest haystack: the billions of pages on the World Wide Web.......一起来看看 《Nine Algorithms That Changed the Future》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

SHA 加密
SHA 加密

SHA 加密工具

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具