Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I declare a class level function in Swift?

Tags:

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?

like image 779
Logan Avatar asked Jun 03 '14 05:06

Logan


People also ask

How do you declare a class variable in Swift?

Declaring VariablesYou begin a variable declaration with the var keyword followed by the name of the variable. Next, you add a colon, followed by the variable type. Afterward, you can assign a value to the variable using the (=) assignment operator.

What is class function Swift?

Languages that support first class functions enable you to use functions and methods just like any other object or value. You can pass them as arguments, save them in properties or return them from another function. In order words, the language treats functions as "first class citizens".

How do you instantiate a class in Swift?

Instantiating an instance of a class is very similar to invoking a function. To create an instance, the name of the class is followed by a pair of parentheses, and the return value is assigned to a constant or variable. In our example, the constant john now points to an instance of the Person class.


2 Answers

Yes, you can create class functions like this:

class func someTypeMethod() {     //body } 

Although in Swift, they are called Type methods.

like image 54
Connor Avatar answered Nov 11 '22 08:11

Connor


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.

like image 30
mythz Avatar answered Nov 11 '22 08:11

mythz