Niels
Niels

Reputation: 1603

Swift Class Functions

So I am wondering about class functions and "normal instance functions". I would like to know what is the purpose of a class function. Is it just so one can use certain functions without assigning the class to a variable first or does it have other purposes?

class Dog {
    func bark()->String{
        return "Woef Woef!"
    }
    class func bark_class()->String{
        return "Woef Woef!"
    }
}

var dog = Dog()
dog.bark() // Woef Woef!

Dog.bark() // Throws and error
Dog.bark_class() // Woef Woef! > Apparently is doens't need an initiated object

Upvotes: 17

Views: 21599

Answers (2)

Antonio
Antonio

Reputation: 72760

Static methods can be invoked without providing an instance of a class - they just need the class type:

Dog.bark_class()

The reason why they exist is because in some cases an instance is not really needed. Generally an instance method that can be moved outside of the class as a global function is a good candidate for being a static method. Another way to figure out if a method can be made static is by examining its body - if it never references a class property or method, then it can be made static. Another obvious difference is that a static method cannot directly access instance properties and methods - in order to do that an instance of the class must either be passed in as a parameter or instantiated in the body.

Instance methods are actually static methods as well, with the difference that they are curried functions taking a class instance as their first parameter:

var dog = Dog()
Dog.bark(dog)()

but which can be more concisely invoked using the traditional syntax:

dog.bark()

I explicitly talked about classes, but what said is also valid for structs - with the only difference that the static keyword is used in place of class when defining static methods.

Upvotes: 23

Bas
Bas

Reputation: 4551

To call your method bark you have to make an instance of the class.

var instance = Dog()

Then you say instance.bark()

You don't need to make an instance when you want to call a class func. Like you said you just can call it with:

Dog.bark_class()

A Class fun is also called a Type Method

Apple docs:

Instance methods, as described above, are methods that are called on an instance of a particular type. You can also define methods that are called on the type itself. These kinds of methods are called type methods. You indicate type methods for classes by writing the keyword class before the method’s func keyword, and type methods for structures and enumerations by writing the keyword static before the method’s func keyword.

Upvotes: 9

Related Questions