【发布时间】:2014-06-06 17:54:46
【问题描述】:
Objective-C 中的类(或静态)方法是在声明中使用 + 完成的。
@interface MyClass : NSObject
+ (void)aClassMethod;
- (void)anInstanceMethod;
@end
如何在 Swift 中实现这一点?
【问题讨论】:
标签: swift
Objective-C 中的类(或静态)方法是在声明中使用 + 完成的。
@interface MyClass : NSObject
+ (void)aClassMethod;
- (void)anInstanceMethod;
@end
如何在 Swift 中实现这一点?
【问题讨论】:
标签: 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
【讨论】:
class 关键字。
它们在 Swift 中被称为类型属性和类型方法,您可以使用 class 关键字。
在 swift 中声明一个类方法或类型方法:
class SomeClass
{
class func someTypeMethod()
{
// type method implementation goes here
}
}
访问该方法:
SomeClass.someTypeMethod()
或者你可以参考Methods in swift
【讨论】:
如果是类,则在声明前添加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))
}
}
....
}
【讨论】:
如果是函数,则在声明前加上 class 或 static,如果是属性,则在声明前加上 static。
class MyClass {
class func aClassMethod() { ... }
static func anInstanceMethod() { ... }
static var myArray : [String] = []
}
【讨论】: