深入理解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关键字》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

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

结网

结网

王坚 / 人民邮电出版社 / 2010-4 / 55.00元

本书作者一直从事互联网产品的研究和实战,经验丰富,同时作为导师,指导了大量优秀的产品经理,本书的内容也是作者8年来培养产品经理新兵的经验集萃。如果你缺乏培养产品经理的教材,本书正好总结了产品经理知识体系,无疑是你很好的选择。 本书覆盖了相当全面的互联网知识,对于想要了解互联网行业或想要借助互联网进行营销的人来说,都是很好的入门读物。 本书并不是一本完善的互联网创业指南,而是写给胸怀互联......一起来看看 《结网》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

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

在线XML、JSON转换工具

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具