Objective-C中的类(或静态)方法是+在声明中完成的.
@interface MyClass : NSObject
+ (void)aClassMethod;
- (void)anInstanceMethod;
@end
Run Code Online (Sandbox Code Playgroud)
如何在Swift中实现这一目标?
Pas*_*cal 148
它们被称为类型属性和类型方法,您可以使用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
Run Code Online (Sandbox Code Playgroud)
Roh*_*hit 20
它们在Swift中被称为类型属性和类型方法,您使用class关键字.
在swift中声明一个类方法或Type方法:
class SomeClass
{
class func someTypeMethod()
{
// type method implementation goes here
}
}
Run Code Online (Sandbox Code Playgroud)
访问该方法:
SomeClass.someTypeMethod()
Run Code Online (Sandbox Code Playgroud)
Ana*_*ile 13
class如果它是一个类,或者static如果它是一个结构,则在前面加上声明.
class MyClass : {
class func aClassMethod() { ... }
func anInstanceMethod() { ... }
}
Run Code Online (Sandbox Code Playgroud)