Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Guard in an Init?

Tags:

swift

Everything works swimmingly except for when I do a random string like "fds", how would I correctly and efficiently use a guard to protect from this sort of error?

enter image description here

init(weatherData: [String: AnyObject]) {
    city = weatherData["name"] as! String

    let weatherDict = weatherData["weather"]![0] as! [String: AnyObject]
    description = weatherDict["description"] as! String
    icon = weatherDict["icon"] as! String

    let mainDict = weatherData["main"] as! [String: AnyObject]
    currentTemp = mainDict["temp"] as! Double
    humidity = mainDict["humidity"] as! Int

    let windDict = weatherData["wind"] as! [String: AnyObject]
    windSpeed = windDict["speed"] as! Double
}
like image 516
Casey Avatar asked Dec 23 '22 20:12

Casey


1 Answers

how would I correctly and efficiently use a guard to protect from this sort of error?

Why would you want to? If the caller does not hand you a dictionary whose "name" key is present and is a string, you are dead in the water because you cannot initialize city. You want to crash.

If you would like to escape from this situation without actually crashing, then make this a failable initializer and fail (return nil) if the dictionary doesn't contain the needed data. This effectively pushes the danger of crashing onto the caller, because the result will be an Optional that might be nil, and the caller must check for that.

init?(weatherData: [String: AnyObject]) {
    guard let city = weatherData["name"] as? String else {return nil}
    self.city = city
    // ... and so on ...
}

But what I would do is none of those things. I would rewrite the initializer as init(city:description:icon:currentTemp:humidity:windSpeed:) and force the caller to parse the dictionary into the needed data. That way, if the data is not there, we don't even try to initialize this class in the first place. My argument would be that it is the caller's job to parse the dictionary; this class should have no knowledge of the structure of some complex dictionary pulled off the Internet (or whatever the source is).

like image 99
matt Avatar answered Jan 08 '23 08:01

matt