Logan
Logan

Reputation: 53112

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?

Upvotes: 62

Views: 44756

Answers (5)

pravin salame
pravin salame

Reputation: 349

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".

Upvotes: 4

mythz
mythz

Reputation: 143339

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.

Upvotes: 38

lucaslt89
lucaslt89

Reputation: 2451

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.

Upvotes: 4

k06a
k06a

Reputation: 18785

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"
    }
}

Upvotes: 15

Connor
Connor

Reputation: 64644

Yes, you can create class functions like this:

class func someTypeMethod() {
    //body
}

Although in Swift, they are called Type methods.

Upvotes: 111

Related Questions