Logan Logan - 5 months ago 11
Swift Question

How do I declare a class level function in Swift?

I can't seem to find it in the docs, and I'm wondering if it exists in native Swift. For example, I can call a class level function on an

NSTimer
like so:

NSTimer.scheduledTimerWithTimeInterval(0.2, target: self, selector: "someSelector:", userInfo: "someData", repeats: true)


But I can't seem to find a way to do it with my custom objects so that I could call it like:

MyCustomObject.someClassLevelFunction("someArg")


Now, I know we can mix Objective-C w/ Swift and it's possible that the
NSTimer
class method is a remnant from that interoperability.

Question




  1. Do class level functions exist in Swift?

  2. If yes, how do I define a class level function in Swift?


Answer

Yes, you can create class functions like this:

class func someTypeMethod() {
    //body
}

Although in Swift, they are called Type methods.

Comments