Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 514
Niels Avatar asked Jan 24 '15 19:01

Niels


People also ask

What is a class function in Swift?

Class functions (not instance methods) are also static functions but they are dynamically dispatched and can be overridden by subclasses unlike static functions.

What is Swift first class function?

Swift has first-class functions, which means that: functions can be stored in constants and variables. functions can be passed as arguments to other functions. functions can be returned by other functions.

What are functions Swift?

Functions are self-contained chunks of code that perform a specific task. You give a function a name that identifies what it does, and this name is used to “call” the function to perform its task when needed.

What are classes and functions?

Classes are used to define the operations supported by a particular class of objects (its instances). If your application needs to keep track of people, then Person is probably a class; the instances of this class represent particular people you are tracking. Functions are for calculating things.


1 Answers

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.

like image 142
Bas Avatar answered Nov 15 '22 21:11

Bas