Md.Muzahidul Islam Md.Muzahidul Islam - 3 months ago 14
Swift Question

What is the importance of class function in Swift?

Consider the class bellow:

class Downloader {

class func downloadImageWithURL(url:String) -> UIImage! {
let data = NSData(contentsOfURL: NSURL(string: url)!)
return UIImage(data: data!)
}

}


What is the advantages of declare the
downloadImageWithURL
as class method rather than instance method?

Answer

If you want to call this Type Method, you write

Downloader.downloadImageWithURL(...)

If it is an Instance Method, you need to create a object first:

let downloader: Downloader = Downloader()
downloader.downloadImageWithURL(...)

In other languages (e.g. C++, Java) you would talk about static vs. non-static functions.

There is no advantage or disadvantages per se, it is an design decision, a very important one! A rule of thumb which came to my mind right now: If there is no need to maintain a state information, go for type methods, otherwise use instance methods.¹

Read more about these methods in Swift Langauge Reference.


¹ At the same time I wrote this rule of thumb, some counter examples came to my mind. So please consider this as a very rough rule of thumb and read some better introductions on object oriented design.