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

如何在Swift中创建类方法/属性?,swift,Swift,Objective-C中的类(或静态)方法是使用声明中的+实现的 @interface MyClass : NSObject + (void)aClassMethod; - (void)anInstanceMethod; @end 如何在Swift中实现这一点?如果是类,则在声明前加上class,如果是结构,则在声明前加上static class MyClass : { class func aClassMethod() { ... } func anInstanceMe

Objective-C中的类(或静态)方法是使用声明中的
+
实现的

@interface MyClass : NSObject

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

@end

如何在Swift中实现这一点?

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

class MyClass : {

    class func aClassMethod() { ... }
    func anInstanceMethod()  { ... }
}
它们被调用,您可以使用
静态
关键字

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 1.1没有存储的类属性。您可以使用closure类属性来实现它,该属性获取绑定到类对象的关联对象。(仅适用于从NSObject派生的类。)


如果声明是函数,则用class或static作为前缀;如果声明是属性,则用static作为前缀

class MyClass {

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

这里不需要
func
关键字吗?当然。我站在拥挤的公共汽车上回答问题,哈哈。更正。简洁的回答。新一代Objective-C代码可能没有移植,但其中一个被忽视的方面是,下一个人可能不得不将其移植到某个版本的Swift。这是很有帮助的,因为我已经完全忘记了Obj-C中类方法的概念,我正在移植一些混乱的东西。我不认为它仅限于游乐场,它也不在应用程序中编译。@ErikKerber很高兴知道,还不需要它们,所以我还没有测试过自己,谢谢。Xcode 6.2仍然针对“class var varName:Type”形式的任何内容报告“尚未支持的类变量”。在Swift 2.0+中,在函数或计算类型属性之前不需要
class
关键字。我一直在学习Swift,不知道是否可以将关联对象附加到Swift类实例。听起来答案是“有点”。(是的,但仅限于作为NSObject子类的对象。)感谢您为我解决此问题。(投票)非常感谢!它甚至比Objective-C中的NSObject类更容易,而且已经很容易设置了。
class MyClass {

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