我似乎无法在文档中找到它,我想知道它是否存在于原生Swift中.例如,我可以NSTimer
像这样调用类级函数:
NSTimer.scheduledTimerWithTimeInterval(0.2, target: self, selector: "someSelector:", userInfo: "someData", repeats: true)
但我似乎无法找到一种方法来使用我的自定义对象,所以我可以这样称呼它:
MyCustomObject.someClassLevelFunction("someArg")
现在,我知道我们可以将Objective-C与Swift混合使用,并且NSTimer
类方法可能是该互操作性的残余.
Swift中是否存在类级函数?
如果是,我如何在Swift中定义类级别函数?
Connor.. 111
是的,你可以像这样创建类函数:
class func someTypeMethod() { //body }
虽然在Swift中,它们被称为Type方法.
是的,你可以像这样创建类函数:
class func someTypeMethod() { //body }
虽然在Swift中,它们被称为Type方法.
更新:感谢@Logan
使用Xcode 6 beta 5,您应该为类使用static
关键字和class
关键字:
class Foo { class func Bar() -> String { return "Bar" } } struct Foo2 { static func Bar2() -> String { return "Bar2" } }
您可以使用以下内容在类中定义Type方法:
class Foo { class func Bar() -> String { return "Bar" } }
然后从类Name中访问它们,即:
Foo.Bar()
在Swift 2.0中,您可以使用static
关键字来阻止子类覆盖该方法.class
将允许子类重写.