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
Class functions (not instance methods) are also static functions but they are dynamically dispatched and can be overridden by subclasses unlike static functions.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With