2

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?

1
  • In short: you dont need to make a object if the function is declared as class function. Therefore - saving memory Commented Aug 31, 2016 at 6:55

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

Instance methods work on a concrete instance of the given class, type methods don't.

You cannot call an instance method without a instance, obviously. But it's not just a performance decision, it's more about communicating what the method is or does.

A good rule of thumb is: if you do not access any of the (instance) properties of the class, it probably should be a type method. Factory methods are a good example of type methods, but also anything that is closely related to the class but not tied to an instance.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.