如何在Swift中声明类级函数?

Log*_*gan 62 swift

我似乎无法在文档中找到它,我想知道它是否存在于原生Swift中.例如,我可以NSTimer像这样调用类级函数:

NSTimer.scheduledTimerWithTimeInterval(0.2, target: self, selector: "someSelector:", userInfo: "someData", repeats: true)
Run Code Online (Sandbox Code Playgroud)

但我似乎无法找到一种方法来使用我的自定义对象,所以我可以这样称呼它:

MyCustomObject.someClassLevelFunction("someArg")
Run Code Online (Sandbox Code Playgroud)

现在,我知道我们可以将Objective-C与Swift混合使用,并且NSTimer类方法可能是该互操作性的残余.

  1. Swift中是否存在类级函数?

  2. 如果是,我如何在Swift中定义类级别函数?

Con*_*nor 111

是的,你可以像这样创建类函数:

class func someTypeMethod() {
    //body
}
Run Code Online (Sandbox Code Playgroud)

虽然在Swift中,它们被称为Type方法.

  • 如何在其中一个类型方法中使用类变量而不使用`<object> .type没有名为<class var>`的成员? (3认同)

myt*_*thz 38

您可以使用以下内容在类中定义Type方法:

class Foo {
    class func Bar() -> String {
        return "Bar"
    }
}
Run Code Online (Sandbox Code Playgroud)

然后从类Name中访问它们,即:

Foo.Bar()
Run Code Online (Sandbox Code Playgroud)

在Swift 2.0中,您可以使用static关键字来阻止子类覆盖该方法.class将允许子类重写.


k06*_*06a 15

更新:感谢@Logan

使用Xcode 6 beta 5,您应该为类使用static关键字和class关键字:

class Foo {
    class func Bar() -> String {
        return "Bar"
    }
}

struct Foo2 {
    static func Bar2() -> String {
        return "Bar2"
    }
}
Run Code Online (Sandbox Code Playgroud)