Reputation: 37
I'm new to coding, apologies for dumb question.
Am following a tutorial to build a note taking app using Swift in Xcode.
Within a class definition I have been defining methods using the keyword func myMethod etc. At one point the instructor decides to define a Class method (within the existing class) using class func myMethod.
Why would you do this?
Thanks in advance for any feedback.
Upvotes: 2
Views: 641
Reputation: 4184
The static (class) function is callable without needing an instance of the class available; it may be called without having to instantiate an object.
This can be useful for encapsulation (avoiding placing the function in the global namespace), or for operations that apply to all objects of a given class, such as tracking the total number of objects currently instantiated.
Static functions can be used to define a namespaces collection of related utility functions:
aDate = Utils.getDate()
aTime = Utils.getTime()
Another common use is for the singleton pattern, where a static function is used to provide access to an object that is limited to being instantiate only once:
obj = MySingleton.getInstance()
obj.whatever()
Upvotes: 0
Reputation: 7373
By defining a class method it means that you don't need an instance of that class to use the method. So instead of:
var myInstance: MyClass = MyClass()
myInstance.myMethod()
You can simply use:
MyClass.myMethod()
Upvotes: 1
Reputation: 22651
This is Swift's take on static methods:
Static methods are meant to be relevant to all the instances of a class (or no instances) rather than to any specific instance.
An example of these are the animation functions in UIView
, or the canSendMail
function from MFMailComposeViewController
.
Upvotes: 0
Reputation: 8216
One answer is namespacing. If a function is only relevant to a certain class there is no need to declare the function globally.
Upvotes: 0