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

Eri*_*ber 95 swift

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

@interface MyClass : NSObject

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

@end
Run Code Online (Sandbox Code Playgroud)

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

Pas*_*cal 148

它们被称为类型属性类型方法,您可以使用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
Run Code Online (Sandbox Code Playgroud)

  • 我不认为它仅限于Playground,它也不会在应用程序中编译. (5认同)
  • @ErikKerber他们现在正在新的测试版中工作. (2认同)

Roh*_*hit 20

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

class SomeClass 
{
     class func someTypeMethod() 
     {
          // type method implementation goes here
     }
}
Run Code Online (Sandbox Code Playgroud)

访问该方法:

SomeClass.someTypeMethod()
Run Code Online (Sandbox Code Playgroud)

或者您可以在swift中引用方法


Ana*_*ile 13

class如果它是一个类,或者static如果它是一个结构,则在前面加上声明.

class MyClass : {

    class func aClassMethod() { ... }
    func anInstanceMethod()  { ... }
}
Run Code Online (Sandbox Code Playgroud)