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 trialpeter keves
6,854 Pointsso basically getter method is same thing as computed property ?
I dont understand the difference between computed and getter method ? aren't they same ? do we need to specify get ? because in first video we didn't I'm confused
1 Answer
Martin Wildfeuer
Courses Plus Student 11,071 PointsYes, you are right, as soon as you use a custom getter and/or setter method with a variable, it is a computed property, as opposed to a stored property. From apple dev docs:
Unlike stored named values and stored variable properties, the value of a computed named value or a computed property is not stored in memory
That is, computed properties can not store and return a value associated with itself, but are rather used to manipulate other stored properties indirectly and/or return a custom value.
<sub><sup>This is quite confusing when coming from a language like Objective-C or Java, where you use getters and setters to manipulate a backing variable (in case of Objective-C normally an instance variable with underscore _
prefix), so I hope the above makes things clearer.</sup></sub>
The question that arises here is: When to use computed properties vs. functions?
Have a look at this stack overflow thread. Here is a simple playground example when I would prefer a computed property over a function, for the sake of simplicity
// Stored properties
var firstName: String = "First"
var lastName: String = "Last"
// Computed property
var fullName: String {
return "\(firstName) \(lastName)"
}
// Getting the property
fullName
// Alternatively, you could use a function
func fullName() -> String {
return "\(firstName) \(lastName)"
}
// Getting fullName
fullName()
Properties can also be observed, like explained here.