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 Swift Enums and Structs Enums and their Methods Methods or Member Functions

Why do I have to set a variable before calling the function?

enum Cars: Int { case Mustang = 1 case Fiesta case Camaro case Ferrari case Porsche case Lola case Manicour

func carRawValue (getnumber: Int) -> String {

    println (Cars(rawValue: getnumber))

    return "Found"
}

}

var test = Cars.Camaro test.carRawValue(1)


Why it is necessary to create a variable TEST to then call the function with a variable.

Why I cant do this "Cars.carRawValue(1)"? Call the enum directly and ask for my function?

Variables are never necessary to use in code, its just alot more convenient. It is possible to make any type of application with no variables in the code at all, but that would take alot longer than to make an application that did contain variables in its code. In this case, it is convenient to use the variable test because every time you want to test to see if it works all you have to do is rewrite the word "test" instead of writing a whole another line of code. Hope this helps clear any confusion.

Thanks Anthony, that was helpful.

But can you give an example of how to call the method "foundCar" without creating and then using a constant or variable?

enum Cars: Int { case Mustang = 1, Fiesta, Camaro, Ferrari, Porsche, Lola, Manicour func foundCar () -> String { return "Found" } }

I'm sorry but what do you mean by this?

1 Answer

Stepan Ulyanin
Stepan Ulyanin
11,318 Points

Hi, when you declare your enum it just writes a rule for the compiler how to act if it will come across this enum So, basically, when you make a variable:

var test = Cars.Camaro

and then you operate on the instance of the car (object):

test.carRawValue(1)

You create an instance of the enum, and then the compiler is able to operate on this instance using the methods you declared in the enumerator. See it this way: You have an instruction on how to operate a car written on paper, BUT if you don't have a car, then you can't operate on it using this instruction, so what you want to do is: instantiate the car (real world analogy: buy, build) and then use the instruction to operate on it, hope it helps!