How do I declare a class level function in Swift?

Swift

Swift Problem Overview


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?

Swift Solutions


Solution 1 - Swift

Yes, you can create class functions like this:

class func someTypeMethod() {
    //body
}

Although in Swift, they are called Type methods.

Solution 2 - Swift

You can define Type methods inside your class with:

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

Then access them from the class Name, i.e:

Foo.Bar()

In Swift 2.0 you can use the static keyword which will prevent subclasses from overriding the method. class will allow subclasses to override.

Solution 3 - Swift

UPDATED: Thanks to @Logan

With Xcode 6 beta 5 you should use static keyword for structs and class keyword for classes:

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

struct Foo2 {
    static func Bar2() -> String {
        return "Bar2"
    }
}

Solution 4 - Swift

you need to define the method in your class

 class MyClass 
 {
       class func myString() -> String
       {
           return "Welcome"
       }
}

Now you can access it by using Class Name eg:

   MyClass.myString()

this will result as "Welcome".

Solution 5 - Swift

From the official Swift 2.1 Doc:

> You indicate type methods by writing the static keyword before the method’s func keyword. Classes may also use the class keyword to allow subclasses to override the superclass’s implementation of that method.

In a struct, you must use static to define a Type method. For classes, you can use either static or class keyword, depending on if you want to allow your method to be overridden by a subclass or not.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLoganView Question on Stackoverflow
Solution 1 - SwiftConnorView Answer on Stackoverflow
Solution 2 - SwiftmythzView Answer on Stackoverflow
Solution 3 - Swiftk06aView Answer on Stackoverflow
Solution 4 - Swiftpravin salameView Answer on Stackoverflow
Solution 5 - Swiftlucaslt89View Answer on Stackoverflow