0
votes

I'm parsing json data using SwiftyJson from a weather API. And i have a list of optional data that i added it to a single guard statement to make the code look simpler and more effective. But unfortunately in the list of optionals i sometimes have nil values from the parsed API data, so the statement goes to else and returns nothing. Do i have to put guard else statements to every optional or there is a way to continue and return the found non nil values in the else statement?

Here is my code:

dispatch_async(dispatch_get_main_queue(), {
                 let jsonContent = JSON(data: data!)

                 guard  let cTemp = jsonContent["currently"]["temperature"].double,
                        let cFeelsLike = jsonContent["currently"]["apparentTemperature"].double,
                        let cHumidity = jsonContent["currently"]["humidity"].double,
                        let cDewPoint = jsonContent["currently"]["dewPoint"].double,
                        let cPressure = jsonContent["currently"]["pressure"].double,
                        let cVisibility = jsonContent["currently"]["visibility"].double,
                        let cWindSpeed = jsonContent["currently"]["windSpeed"].double,
                        let cWindDirection = jsonContent["currently"]["windBearing"].double,
                        let cRainChance = jsonContent["currently"]["precipProbability"].double,
                        let cIconString = jsonContent["currently"]["icon"].string,
                        let cSummary = jsonContent["currently"]["summary"].string,
                        let cDailySummary = jsonContent["daily"]["summary"].string

                        else{

                            self.messageFrame.removeFromSuperview()
                          return
                        }

Here is the code after parsing the data that changes the labels on the storyboard.

 if self.segmentedControl.selectedSegmentIndex == 0 {
                    UIApplication.sharedApplication().applicationIconBadgeNumber = Int(round(cTemp))
                    self.tempLabel.text = String(Int(round(cTemp))) + "˚"
                    self.humidityLabel.text = String(Int(round(cHumidity*100))) + "%"
                    self.pressureLabel.text = String(Int(round(cPressure))) +  NSLocalizedString(" mBar", comment: "milli Bar")
                    self.windSpeedLabel.text = String(Int(round(cWindSpeed))) + NSLocalizedString(" Km/h", comment: "Kilo fe El sa3a")
                    self.realFeelLabel.text = String(Int(round(cFeelsLike))) + "˚"
                    self.windDirectionLabel.text = self.windDirectionNotation(cWindDirection)
                    self.rainChanceLabel.text = String(Int(round(cRainChance * 100))) + "%"
               //     self.visibilityLabel.text = String(Int(round(cVisibility))) + NSLocalizedString(" Km", comment: "Km")
                    self.descriptionLabel.text = cSummary
                    self.descriptionMoreLabel.text = cDailySummary
                    self.bgImage.image = self.bgPicker(cIconString) //Change BG according to currently weather conditions.

                } else {
                    self.tempLabel.text = String(Int(round(cTemp))) + "˚"
                    self.humidityLabel.text = String(Int(round(cHumidity*100))) + "%"
                    self.pressureLabel.text = String(Int(round(cPressure))) + NSLocalizedString(" mBar", comment: "milli Bar")
                    self.windSpeedLabel.text = String(Int(round(cWindSpeed))) + NSLocalizedString(" mph", comment: "meel fee el sa3a")
                    self.realFeelLabel.text = String(Int(round(cFeelsLike))) + "˚"
                    self.windDirectionLabel.text = self.windDirectionNotation(cWindDirection)
                    self.rainChanceLabel.text = String(Int(round(cRainChance * 100))) + "%"
              //      self.visibilityLabel.text = String(Int(round(cVisibility))) + NSLocalizedString(" mi", comment: "meel")
                    self.descriptionLabel.text = cSummary
                    self.descriptionMoreLabel.text = cDailySummary
                    self.bgImage.image = self.bgPicker(cIconString) //Change BG according to currently weather conditions.
                }
1
What is it that you want to do if one of the optionals is nil? In other words: if you don't want to abort, why are you testing all these values in the first place? Your cTemp etc. are purely local variables, you are not doing anything with them, so what is the purpose of your code?matt
I want to neglect it and continue the operations. To post the current found data on the storyboard labels. Or maybe i have to try putting all the remaining code in the else statement? But the data will be incomplete. Because it is returning before checking all the optionals found in the guard statement.Kegham K.
Okay, cool. So where's the part where you do that? You need to show that part of your code if you want help rewriting your code.matt
@Matt for instance when i comment out the visibility optional the code works perfect but when the visibility data is nil it returns nothing and the labels are not changed on the storyboard.Kegham K.
Yes, but you have shown no code that changes any labels. I'm asking you to show it.matt

1 Answers

0
votes

It is legal to set a label's text to nil or an Optional string. So for each item, use Optional chaining to unwrap it and set the corresponding label's text.

Unfortunately I don't know SwiftyJSON, but here's how you would do it if this were simply a Dictionary:

// here is some test data
let content = ["currently":["temperature":"21"]]
let lab = UILabel()
// this is what you would do
lab.text = (content["currently"] as? NSDictionary)?["temperature"] as? String

The point is that last line. If we get nil, we set the label's text to nil and no harm done. If we get our string, we set the label's text to an Optional wrapping that string and no harm done.