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 Initializer

When you use self, does it only relate to the instance that it is indented in?

Can someone also tell me bit more about self too, like when to use it and if it has to be used within an initialiser? Thanks

2 Answers

Rafael Robles
Rafael Robles
3,907 Points

A great use would be use self within brackets of the enum class to refer to its own members to simplify your code. Imagine you and your friend have a phone. In code it would look like this.

enum Phone: Double { case IPhone = 9.1 , GalaxyS3 = 8.8, Blackberry = 6.2 }

var myPhone = Phone.IPhone var friendsPhone = Phone.GalaxyS3

Here's what I'm talking about. If you want to know who's phone is better, you would need to create a method in the enum like shown below. (I give an example with and without the use of self. notice the parameters.)

enum Phone: Double { case IPhone = 9.1 , GalaxyS3 = 8.8, Blackberry = 6.2

//Example Without Self
func phoneAnalyzer (myPhone: Phone, friendsPhone: Phone)  -> String{
    if (myPhone.rawValue > friendsPhone.rawValue){
    return "Your Phone is Better"}
    else {
    return "Your friends phone is better"}
}
// the method call would be myPhone.phoneAnalyzer(myPhone, friendsPhone)

//With Self
func phoneAnalyzer (friendsPhone: Phone)  -> String{ //notice more parameters here
    if (self.rawValue > friendsPhone.rawValue){
    return "Your Phone is Better"}
    else {
    return "Your friends phone is better"}

} //Method call with self is myPhone.phoneAnalyzer(friendsPhone) // Less parameters, less redundancy, better readability

Bradley Maskell
Bradley Maskell
8,858 Points

You use self to refer to the instance you are working in.