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

Jorge Velasco
Jorge Velasco
9,997 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
9,997 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