How to declare a class level function in Swift?

I cannot find it in the docs, and I wonder if it exists in native Swift. For example, I can call the class level function on NSTimer as follows:

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

But I cannot find a way to do this with my custom objects, so that I can call it like this:

 MyCustomObject.someClassLevelFunction("someArg") 

Now I know that we can mix Objective-C w / Swift, and it is possible that the NSTimer class NSTimer is the remainder of this compatibility.

Question

  • Are there class level functions in Swift?

  • If so, how to define a class level function in Swift?

+59
swift
Jun 03 '14 at 5:51 on
source share
5 answers

Yes, you can create class functions like this:

 class func someTypeMethod() { //body } 

Although in Swift they are called type methods.

+109
Jun 03 '14 at 5:55
source share

You can define type methods inside your class:

 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 , which will prevent the subclass from being overridden. class allow overriding subclasses.

+37
Jun 04
source share

UPDATED: @Logan

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

 class Foo { class func Bar() -> String { return "Bar" } } struct Foo2 { static func Bar2() -> String { return "Bar2" } } 
+13
Aug 09 '14 at 15:26
source share

From the official Swift 2.1 Doc doc :

You specify type methods by writing a static keyword before the func method keywords. Classes can also use the class keyword to allow subclasses to override the implementation of this class by superclasses.

In the structure, you must use static to define the type method. For classes, you can use the static or class keyword, depending on whether you want to prevent your method from overriding the subclass or not.

+4
09 Oct '15 at 12:37
source share

you need to define a method in your class

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

Now you can access it using the class name, for example:

  MyClass.MyString() 

This will result in "Welcome."

+3
Nov 04 '14 at 8:22
source share



All Articles