使用+
in声明完成了Objective-C中的类(或静态)方法。
@interface MyClass : NSObject
+ (void)aClassMethod;
- (void)anInstanceMethod;
@end
如何在Swift中实现?
使用+
in声明完成了Objective-C中的类(或静态)方法。
@interface MyClass : NSObject
+ (void)aClassMethod;
- (void)anInstanceMethod;
@end
如何在Swift中实现?
Answers:
它们称为类型属性和类型方法,您可以使用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
class
函数或计算类型属性之前添加关键字。
它们在Swift中被称为类型属性和类型方法,您可以使用class关键字。
在swift中声明一个类方法或Type方法:
class SomeClass
{
class func someTypeMethod()
{
// type method implementation goes here
}
}
访问该方法:
SomeClass.someTypeMethod()
class
如果声明是类或static
结构,则在声明前加上。
class MyClass : {
class func aClassMethod() { ... }
func anInstanceMethod() { ... }
}
func
此处的关键字吗?
Swift 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))
}
}
....
}