swift - 在 Init 中使用 Guard?

标签 swift

除了当我执行像“fds”这样的随机字符串时,一切都运行顺畅,我将如何正确有效地使用守卫来防止此类错误?

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
}

最佳答案

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/

相关文章:

swift - 使用闭包时构建失败

ios - Swift 开关展开类型匹配模式

ios - 实例化 Realm 对象时出现 EXC_BAD_INSTRUCTION

swift - 在 SwiftUI 中向 NavigationView 添加搜索栏

ios - UITextView 中的动画 Gif

ios - 保持 UNNotificationContent 几秒钟

ios - 如何将所有值作为 NSArray 返回?来自完成 block 中的查询

swift - 在 Swift 中,Int 是否有一个隐藏的接受字符串的初始化器?

swift - 相对布局。约束方程解释

swift - Realm Swift - 按 ID 查找