Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

iOS Swift 2.0 Enumerations and Optionals Introduction to Enumerations Modeling Finite Data

Whitman Huntley
Whitman Huntley
6,811 Points

Why would I use an object to preform a method? Could somebody give me an example of why I would want to do this?

Pasan mentioned that usually an object would preform the WeekendOrWeekday function. Why? I understand that only an example/near pseudocode is being shown in this video but why would I want to do this when making a proper app

1 Answer

David Papandrew
David Papandrew
8,386 Points

Hi Whitman,

I can give you a few reasons for this.

One is that it makes your code modular. This goes with the concept of grouping/chunking like pieces of code together with other related components. This is useful, especially when your code gets more complex, since it helps organize your code logically. It also makes the code more portable. Need to grab a class from another project and put it and all it's methods in a new project? Just copy and past the class and put it in a swift file in your new project.

Similarly, when you are using different iOS classes like a UITableView, class methods are also very practical. For instance, a UITableView instance might care about how to scroll through a list of items but it probably doesn't care about sprite animation. From a usage and documentation standpoint, it makes sense to have class methods. You don't need a smorgasbord of code to sift through.

In addition to grouping like concerns together, class methods also incorporates some level of safety into your coding (and should make debugging easier). Rather than allowing any object to access a generalized function, only specific classes can access their respective class methods. Added to that is the fact that you can subclass objects and then modify and override those class methods to tailor the code to your needs.

There are probably some other reasons I'm missing but I hope that touches on a few of them.