美文网首页
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

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