我似乎无法在文档中找到它,我想知道它是否存在于原生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
类方法可能是该互操作性的残余.
Swift中是否存在类级函数?
如果是,我如何在Swift中定义类级别函数?
Con*_*nor 111
是的,你可以像这样创建类函数:
class func someTypeMethod() {
//body
}
Run Code Online (Sandbox Code Playgroud)
虽然在Swift中,它们被称为Type方法.
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)