如何在Swift中创建类方法/属性?

时间:2014-06-06 17:54:47

标签: swift

Objective-C中的类(或静态)方法是在声明中使用+完成的。

@interface MyClass : NSObject

+ (void)aClassMethod;
- (void)anInstanceMethod;

@end

如何在Swift中实现这一目标?

5 个答案:

答案 0 :(得分:142)

他们被称为type propertiestype methods,您可以使用classstatic个关键字。

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

答案 1 :(得分:20)

它们在Swift中被称为类型属性和类型方法,您使用class关键字 在swift中声明一个类方法或Type方法:

class SomeClass 
{
     class func someTypeMethod() 
     {
          // type method implementation goes here
     }
}

访问该方法:

SomeClass.someTypeMethod()

或者您可以参考Methods in swift

答案 2 :(得分:13)

如果声明属于某个类,则使用class作为前缀,如果是结构,则使用static

class MyClass : {

    class func aClassMethod() { ... }
    func anInstanceMethod()  { ... }
}

答案 3 :(得分:4)

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))
        }
    }

    ....
}

答案 4 :(得分:4)

如果声明是一个函数,则使用class或static添加声明;如果是属性,则使用static。

class MyClass {

    class func aClassMethod() { ... }
    static func anInstanceMethod()  { ... }
    static var myArray : [String] = []
}
相关问题