Kegham K.
Kegham K.

Reputation: 1614

Guard statements for optionals are nil in swift

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.
                }

Upvotes: 0

Views: 307

Answers (1)

matt
matt

Reputation: 535989

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.

Upvotes: 0

Related Questions