[Objective-C中的类(或静态)方法是在声明中使用+
完成的。
@interface MyClass : NSObject
+ (void)aClassMethod;
- (void)anInstanceMethod;
@end
如何在Swift中实现?
它们分别称为type properties和type methods,并且您使用class
或static
关键字。
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中被称为类型属性和类型方法,您使用class关键字。在swift中声明一个类方法或Type方法:
class SomeClass { class func someTypeMethod() { // type method implementation goes here } }
访问该方法:
SomeClass.someTypeMethod()
或您可以参考Methods in swift
如果是类,则在声明前使用class
,如果是结构,则使用static
。
class MyClass : {
class func aClassMethod() { ... }
func anInstanceMethod() { ... }
}
Swift 1.1没有存储的类属性。您可以使用闭包类属性来实现它,该属性获取与类对象绑定的关联对象。 (仅适用于从NSObject派生的类。)
[如果是函数,则在声明前加上class或static,如果是属性,则使用static。
简单示例类方法,实例方法和静态方法