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

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

内容简介:作用:这两个关键字都是用来说明被修饰的属性或者方法是类型(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关键字》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

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

Cascading Style Sheets 2.0 Programmer's Reference

Cascading Style Sheets 2.0 Programmer's Reference

Eric A. Meyer / McGraw-Hill Osborne Media / 2001-03-20 / USD 19.99

The most authoritative quick reference available for CSS programmers. This handy resource gives you programming essentials at your fingertips, including all the new tags and features in CSS 2.0. You'l......一起来看看 《Cascading Style Sheets 2.0 Programmer's Reference》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具