gpt4 book ai didi

swift - 如何在 Swift 中创建类方法/属性?

转载 作者:IT王子 更新时间:2023-10-29 04:56:41 26 4
gpt4 key购买 nike

Objective-C 中的类(或静态)方法是在声明中使用 + 完成的。

@interface MyClass : NSObject

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

@end

这在 Swift 中如何实现?

最佳答案

它们被称为 type propertiestype methods并使用 classstatic 关键字。

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 - 如何在 Swift 中创建类方法/属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24087936/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com