如何在Swift中制作类方法/属性?


97

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

@interface MyClass : NSObject

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

@end

如何在Swift中实现?

Answers:


152

它们称为类型属性类型方法,您可以使用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

5
我不认为它仅限于Playground,也不能在应用程序中编译。
Erik Kerber 2014年

@ErikKerber很高兴知道,由于不需要它们,所以还没有测试自己,谢谢。
Pascal

Xcode 6.2仍然针对“ class var varName:Type”形式的任何内容报告“尚不支持的类变量”。
Ali Beadle 2015年

在Swift 2.0+中,您不需要在class函数或计算类型属性之前添加关键字。
Govind Rai

20

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

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

访问该方法:

SomeClass.someTypeMethod()

或者您可以快速引用方法


非常感谢!它比Objective-C中的NSObject类更容易,并且已经很容易设置。
Supertecnoboff

14

class如果声明是类或static结构,则在声明前加上。

class MyClass : {

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

您不需要func此处的关键字吗?
Jamie Forrest 2014年

1
当然。请我站在拥挤的公共汽车上回答问题,哈哈。已更正。
Analog File

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

    ....
}

我一直在学习Swift,想知道是否可以将关联对象附加到Swift类实例。听起来答案是“有点”。(是的,但仅是NSObject子类的对象。)感谢您为我解决了该问题。(已投票)
Duncan C

4

如果声明是函数,则在其前面加上cla​​ss或static;如果它是属性,则在其前面加上static。

class MyClass {

    class func aClassMethod() { ... }
    static func anInstanceMethod()  { ... }
    static var myArray : [String] = []
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.