static 和 class

本文介绍了Swift语言中用于描述类型范围作用域的static关键字用法,包括在struct和enum中如何定义类型方法、类型属性等,并通过具体示例进行说明。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Swift 中表示“类型范围作用域”这一概念有两个不同的关键字,它们分别是 static 和 class。
在非 class 的类型上下文中,我们统一使用 static 来描述类型作用域。这包括在 enum 和 struct 中表述类型方法和类型属性时。在这两个值类型中,我们可以在类型范围内 声明并使用存储属性,计算属性和方法。static 适用的场景有这些:

struct PointAB {
    let x : Double
    let y : Double

    // 存储属性
    static let zero = PointAB(x: 0, y: 0)

    // 计算属性
    static var ones: [PointAB] {
        return [PointAB(x: 1, y: 1),
                PointAB(x: -1, y: 1),
                PointAB(x: 1, y: -1),
                PointAB(x: -1, y: -1)]
    }

    // 类型方法
    static func add(p1: PointAB, p2: PointAB) -> PointAB {
        return PointAB(x: p1.x + p2.x, y: p1.y + p2.y)
    }

}

这里写图片描述

protocol MyProtocol {
    static func foo() -> String
}

struct MyStruct:MyProtocol {
    static func foo() -> String {
        return "MyStruct"
    }

}

enum MyEnum:MyProtocol {
    static func foo() -> String {
        return "MyEnum"
    }
}

class MyClass: MyProtocol {
    static func foo() -> String {
        return "MyClass"
    }

}

来自:swift-喵神

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值