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 trialIsmael Barry
3,328 PointsAdding "self" to the initial value inside of the Initialization method
import Foundation
struct Current { var currentTime: Int var temperature: Int var humidity: Int var precipProbability: Int var summary: String var icon: String
init (weatherDictionary:NSDictionary){
let currentWeather = weatherDictionary["currently"]
/* This is what Pasan had in the video */
currentTime = currentWeather["time"] as Int
/* This is what I think would also be fine to write. */
self.currentTime = currentWeather["time"] as Int
}
}
1 Answer
Stone Preston
42,016 PointsYes that would be fine. you can use self in front of the property name, however it is not necessary. you only need to use self to distinguish a property from a parameter when there is a naming conflict or ambiguity. If there is no ambiguity, it is conventional to omit self
the Swift eBook states:
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.
The main exception to this rule occurs when a parameter name for an instance method has the same name as a property of that instance. In this situation, the parameter name takes precedence, and it becomes necessary to refer to the property in a more qualified way. You use the self property to distinguish between the parameter name and the property name.
Here, self disambiguates between a method parameter called x and an instance property that is also called x:
struct Point {
var x = 0.0, y = 0.0
func isToTheRightOfX(x: Double) -> Bool {
return self.x > x
}
}
Ismael Barry
3,328 PointsIsmael Barry
3,328 PointsOk, that makes sense now. I remember taking note of that. Thanks a lot Stone for the help and quick response. I really appreciate it!
Stone Preston
42,016 PointsStone Preston
42,016 Pointsno problem