Objective-C中的类方法(或静态方法)是通过在声明中使用+
来实现的。
@interface MyClass : NSObject
+ (void)aClassMethod;
- (void)anInstanceMethod;
@end
如何在Swift中实现此功能?
Objective-C中的类方法(或静态方法)是通过在声明中使用+
来实现的。
@interface MyClass : NSObject
+ (void)aClassMethod;
- (void)anInstanceMethod;
@end
如何在Swift中实现此功能?
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中声明类方法或类型方法:
class SomeClass
{
class func someTypeMethod()
{
// type method implementation goes here
}
}
访问该方法:
SomeClass.someTypeMethod()
或者您可以参考Swift中的方法
如果是类,请在声明前添加class
;如果是结构体,请在声明前添加static
。
class MyClass : {
class func aClassMethod() { ... }
func anInstanceMethod() { ... }
}
func
关键字吗? - Jamie ForrestSwift 1.1没有存储类属性。您可以使用一个闭包类属性来实现它,该属性获取与类对象绑定的关联对象。(仅适用于从NSObject派生的类。)
private var fooPropertyKey: Int = 0 // value is unimportant; we use var's address
class YourClass: SomeSubclassOfNSObject {
class var foo: FooType? { // Swift 1.1 doesn't have stored class properties; change when supported
get {
return objc_getAssociatedObject(self, &fooPropertyKey) as FooType?
}
set {
objc_setAssociatedObject(self, &fooPropertyKey, newValue, objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN_NONATOMIC))
}
}
....
}
如果是函数声明,使用class或static修饰词,如果是属性声明,使用static修饰词。
class MyClass {
class func aClassMethod() { ... }
static func anInstanceMethod() { ... }
static var myArray : [String] = []
}