如果没有值,则使用guard let语句

时间:2017-10-12 11:31:10

标签: swift xcode

在下面的代码中,在从不使用else语句之后给出警告经度和纬度,如果我的字典不包含经度和纬度的值,则将它们设置为let longitude = Double(151.209900)并让纬度=双倍(-33.865143)?或者我是否在使用警卫语言

做错了什么
guard let dictionary = snapshot.value as? [String : AnyObject] else { return }
guard let latitude = dictionary["Latitude"] as? String else {
    let latitude = Double(-33.865143)            
    return 
}
guard let longitude = dictionary["Longitude"] as? String else {
    let longitude = Double(151.209900)
    return 
}       
guard let latDouble = Double(latitude) else { return }
guard let longDouble = Double(longitude) else { return }

1 个答案:

答案 0 :(得分:3)

永远不会使用为纬度和经度设置的值,因为它们的范围仅限于guard

我可能会这样做:

guard let dictionary = snapshot.value as? [String : AnyObject] else { return }


let latitude = Double(dictionary["Latitude"] as? String ?? "-33.865143")
let longitude = Double(dictionary["Longitude"] as? String ?? "151.209900")