Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

Creating a Data Model - Struct vs Class

Hello!

I've just started working on my own app, a calories counter for salads. While the app is not that feature rich, I am having a hard time deciding if I should model a class Vegetables and then subclass each vegetable like Tomato, Cucumber etc from it or if I should go ahead and use a Struct and not use iheritance at all given the fact that all onjects will have the same member values: Name, Color, Vitamins, Calories...

I do not know Core Data nor Ntwroking and remote Databases for now I just want to hardocde everything in the App.

Any ideas / suggestions?

3 Answers

The question is Do you really need to create subclasses for Tomato, Cucumber etc. Maybe Vegetable is enough here.

Maybe even something like this:

import UIKit

struct Vegetable {
    let name: Vegetable.Name
    let color: UIColor
    let vitamins: [Vitamin]

    enum Name: String, CustomStringConvertible {
        case tomato
        case cucumber
        case broadBean

        var description: String {
            switch self {
            case .broadBean:
                return "broad bean"
            default:
                return self.rawValue
            }
        }
    }
}

enum Vitamin: String {
    case a
    case b
    //...
}

With enums the compiler will be able to prevent any typos before running the code. And we can ensure that if we need an image, we can simply do this:

extension Vegetable {
   var image: UIImage {
      return UIImage(named: self.name.rawValue)!
      /* We can force unwrap this because it will only crash
        in case there is no image file corresponding
        to Vegetable.Name enum raw string value. */
   }
}

✝ As of Swift 3, enum cases should be written with first letter being in lowercase.

If you have any questions about the code, just ask =)

As for deciding between using class or struct, structs are usually used to represent data, and classes to represent things that perform actions.

UIViewController is a class because it 1) heavily relies on class hierarchy and 2) has lots of methods that are used to perform actions.

CGPoint is a struct because the only thing it really needs to do is to hold data. It only has two methods, one of which, for example, is to make it possible to check two CGPoints for equality.

Thank you very much for the clarification!