除了当我执行像“fds”这样的随机字符串时,一切都运行顺畅,我将如何正确有效地使用守卫来防止此类错误?
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
}
最佳答案
how would I correctly and efficiently use a guard to protect from this sort of error?
你为什么要这样做?如果调用者没有给你一个字典,它的 "name"
键存在并且是一个字符串,你就完蛋了,因为你无法初始化 city
。你想要崩溃。
如果您想在不实际崩溃的情况下摆脱这种情况,则将其设置为可失败初始化器并在字典不包含需要的数据。这有效地将崩溃的危险推给了调用者,因为结果将是一个可能为 nil
的 Optional,调用者必须检查它。
init?(weatherData: [String: AnyObject]) {
guard let city = weatherData["name"] as? String else {return nil}
self.city = city
// ... and so on ...
}
但是我不会做这些事情。我会将初始化程序重写为 init(city:description:icon:currentTemp:humidity:windSpeed:)
并强制调用者将字典解析为所需的数据。这样,如果数据不存在,我们甚至不会首先尝试初始化此类。我的论点是,解析字典是调用者的工作; 这个类应该不知道从 Internet 上提取的一些复杂词典的结构(或任何来源)。
关于swift - 在 Init 中使用 Guard?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42125036/