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

问题描述 投票:95回答:6

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

@interface MyClass : NSObject

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

@end

如何在Swift中实现?

swift
6个回答
149
投票

它们分别称为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

20
投票

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

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

访问该方法:

SomeClass.someTypeMethod()

或您可以参考Methods in swift


13
投票

如果是类,则在声明前使用class,如果是结构,则使用static

class MyClass : {

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

4
投票

Swift 1.1没有存储的类属性。您可以使用闭包类属性来实现它,该属性获取与类对象绑定的关联对象。 (仅适用于从NSObject派生的类。)


4
投票

[如果是函数,则在声明前加上cla​​ss或static,如果是属性,则使用static。


0
投票

简单示例类方法,实例方法和静态方法

© www.soinside.com 2019 - 2024. All rights reserved.