美文网首页
Swift-guard

Swift-guard

作者: lotawei | 来源:发表于2017-10-17 10:06 被阅读9次

swift 中guard具体的好处

用它避免繁杂的逻辑判断
如:
guard
let name = json["city"] as? String,
let latitude = json["latitude"] as? Double,
let longitude = json["longitude"] as? Double,
let sunriseString = json["sunrise"] as? String,
let sunsetString = json["sunset"] as? String,
let sunrise = DateFormatter.isoDateFormatter.date(from: sunriseString),
let sunset = DateFormatter.isoDateFormatter.date(from: sunsetString)
else {
fatalError("Could not instantiate a city from JSON: (json)")
}
let coordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
guard CLLocationCoordinate2DIsValid(coordinate) else {
fatalError("City has invalid coordinates: (coordinate)")
}
解析字段可能失败的情况下绕过恶心的if else 嵌套,只检测不满足条件的结果处理

相关文章

  • Swift-guard

    swift 中guard具体的好处 用它避免繁杂的逻辑判断如:guardlet name = json["city...

  • swift-guard

    guard可以理解我简化了判断句,以在判断一个条件为true的情况下执行某语句,否则终止或跳过执行某语句 guar...

  • Swift-guard

    swift中的guard是如何工作的

  • Swift-guard语句

    guard语句(如if语句)根据表达式的布尔值执行语句。 您使用保护语句要求条件必须为真,以便在执行保护语句后的代...

  • Swift-guard语句

    guard 是 Swift 2 中我最喜爱的特性之一。虽然完全不使用 guard 也没有什么影响,它只是给我们提供...

  • Swift-guard与let

    Swift中类型中加入了?可选类型,因此在每次进行参数判断的时候都要加入是不是为nil的判断,我们通过简单的字符串...

  • Swift-guard关键字

    1.guard关键字必须使用在函数中。2.guard关键字必须和else同时出现。3.guard关键字只有条件为f...

网友评论

      本文标题:Swift-guard

      本文链接:https://www.haomeiwen.com/subject/twiruxtx.html