如何在 Swift 中创建类方法/属性? [英] How do I make class methods / properties in Swift?

查看:43
本文介绍了如何在 Swift 中创建类方法/属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Objective-C 中的类(或静态)方法是在声明中使用 + 实现的.

Class (or static) methods in Objective-C were accomplished using + in declarations.

@interface MyClass : NSObject

+ (void)aClassMethod;
- (void)anInstanceMethod;

@end

如何在 Swift 中实现这一点?

How can this be achieved in Swift?

推荐答案

它们被称为 类型属性类型方法并且您使用classstatic 关键字.

They are called type properties and type methods and you use the class or static keywords.

class Foo {
    var name: String?           // instance property
    static var all = [Foo]()    // static type property
    class var comp: Int {       // computed type property
        return 42
    }

    class func alert() {        // type method
        print("There are \(all.count) foos")
    }
}

Foo.alert()       // There are 0 foos
let f = Foo()
Foo.all.append(f)
Foo.alert()       // There are 1 foos

这篇关于如何在 Swift 中创建类方法/属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆