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 Structs and their Methods Struct Methods

Will Feldman
Will Feldman
3,121 Points

When I take away "self." anywhere it doesn't do anything to the code. It doesn't create bugs or anything. Why?

If I take away all the self.'s nothing happends. No errors. Why?

struct Contact {
    let firstName: String
    let lastName: String
    var type = "Friend"

    init(fName: String, lName: String) {
        firstName = fName
        lastName = lName
    }

    func fullName() -> String {
        return firstName + " " + lastName
    }
}

var person = Contact(fName: "Jon", lName: "Smith")
person.fullName()

Do you need "self."

2 Answers

In Swift, self is not required to access member properties, but it explicitly specifies that you mean the member property instead of a different variable with the same name. For example:

struct Contact {
    let firstName: String

    init(firstName: String) {
        self.firstName = firstName
    }
}

This code works, but if you remove self. from init it becomes unclear which version of firstName you mean.

Great question!

The self Property

Every instance of a type has an implicit property called self, which is exactly equivalent to the instance itself. You use the self property to refer to the current instance within its own instance methods.

func incrementBy(amount: Int, #numberOfTimes: Int) {
    count += amount * numberOfTimes
}

The increment() method in the example above could have been written like this:

func increment() {
    self.count++
}

In practice, you don’t need to write self in your code very often. If you don’t explicitly write self, Swift assumes that you are referring to a property or method of the current instance whenever you use a known property or method name within a method. This assumption is demonstrated by the use of count (rather than self.count) inside the three instance methods for Counter. - Apple

You can read more about it here and here