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!

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 Enumerations and Optionals in Swift Introduction to Enumerations Methods on Enumerations

Jorge Velasco
Jorge Velasco
13,773 Points

I am having a hard time wrapping my had around when to use "self"

Usually I would use it in a Class or Struct knowing that when I call self I mean whenever an instance of that object is called? But now I am seeing it also being used in switch statements and I am having a hard time actually understanding what does "self" actually means here.

I've seen the videos quite a few times and even tried Googling the question but most of the answers use some very big grow-up words. Could someone explain it to me like I am 5 years old please?

Thank you in advanced!

Did you get it

2 Answers

@ Jorge Velasco all it means is the context of the programming for example like you said you saw a self inside a switch well that switch statement could be within a object for example a class called Car

self = the object ( Car )

Jorge Velasco
Jorge Velasco
13,773 Points

That makes sense, thank you!

SivaKumar Kataru
SivaKumar Kataru
2,386 Points

In this case Self Represents the Object Itself. The Method Called Color inside Enum is an Instance method which can be called on an object. Inside Color method there is switch expression with the self condition which means we are telling we want to work on the self object data.

enum BarCode { case upc(Int, Int, Int Int)

func doesSomething() -> Int { switch self { // Switches on Object Itself

case .upc(let u, let p, let c): return u + p + c } } }

let someProduct = Barcode.upc(1,2,3,4) // Now we have initialised an enum member with an associated value someProduct.doesSomething() // Works on the Members itself which are assigned