Skip to content

Instantly share code, notes, and snippets.

@charleshkang
Created January 9, 2017 18:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save charleshkang/2b612fe3abc66c9bf64f33f68f9375e4 to your computer and use it in GitHub Desktop.
Save charleshkang/2b612fe3abc66c9bf64f33f68f9375e4 to your computer and use it in GitHub Desktop.
//
// WeatherParser
// C4QWeather
//
// Created by Charles Kang on 11/21/16.
// Copyright © 2016 Charles Kang. All rights reserved.
//
import Foundation
import SwiftyJSON
class WeatherParser {
//MARK: Action Methods
/**
use flatMap instead of map here because data from a backend can always fail,
so use flatMap so we only return successful weather objects
*/
func parseWeatherJSON(_ json: JSON) -> [Weather] {
let weatherArray = json["response"][0]["periods"].arrayValue
return weatherArray.flatMap { Weather(json: $0) }
}
}
extension Weather {
/**
create a failable initializer to make sure
we only get properties that are valid. also use
guard to take advantage of its early exit features
*/
init?(json: JSON) {
guard let maxTempF = json["maxTempF"].int,
let minTempF = json["minTempF"].int,
let maxTempC = json["maxTempC"].int,
let minTempC = json["minTempC"].int,
let dateTimeISO = json["dateTimeISO"].string
else { return nil }
self.maxTempF = maxTempF
self.minTempF = minTempF
self.maxTempC = maxTempC
self.minTempC = minTempC
self.dateTime = dateTimeISO
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment