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 Build a Weather App with Swift (Retired) Data Modeling With Structures Cleaning Up Our Date

Why did we have to push the initialization of currentTime to the end of the init() method ?

When we declared the constant currentTime as an optional we still had an error until we pushed the initialization of it to the end of the init() method and let the other parameters be declared first. Why is that ?

Code :

struct Current {

    let currentTime : String?
    let temperature : Double
    let precipProbability : Double
    let humidity : Double
    let summary : String
    let icon : String

    init(weatherDictionary: NSDictionary) {

        let currentWeather = weatherDictionary["currently"] as NSDictionary

        self.temperature = currentWeather["temperature"] as Double
        self.precipProbability = currentWeather["precipProbability"] as Double
        self.humidity = currentWeather["humidity"] as Double
        self.summary = currentWeather["summary"] as String
        self.icon = currentWeather["icon"] as String

        let currentTimeIntValue = currentWeather["time"] as Int
        self.currentTime = dateStringFromUnixTime(currentTimeIntValue)

    }

    func dateStringFromUnixTime(unixTime: Int) -> String {
        let timeInSeconds = NSTimeInterval(unixTime)
        let weatherDate = NSDate(timeIntervalSince1970: timeInSeconds)

        let dateFormatter = NSDateFormatter()
        dateFormatter.timeStyle = .ShortStyle

        return dateFormatter.stringFromDate(weatherDate)
    }
}

1 Answer

Well he says that the init has two phases, 1 where it sets the values and the other when it reads instances that are made. So I guess it must go through the first cycle where it sets the values, then the second cycle is where it reads all the instances that are made and since it first set the values it now can input said values into the instance.