I have three conditions:
data.weight
and myoutput
are nil
myoutput
has no value data.weight
and myoutput
both have a value
override func viewWillAppear(_ animated: Bool) { super .viewWillAppear(animated) self.navigationItem.hidesBackButton = true let myOutput = UserDefaults.standard.string(forKey: "height") let dateFormator = DateFormatter() dateFormator.dateFormat = "dd.MM.yyyy" let data = WeightTracker.mr_findFirst(with: NSPredicate(format: "date == %@", dateFormator.string(from: Date()))) as? WeightTracker if myOutput == nil && data?.weight == nil { bmiLabel.text = "--" } else if myOutput == nil && data?.weight != nil { bmiLabel.text = "--" } else { let dateFormator = DateFormatter() dateFormator.dateFormat = "dd.MM.yyyy" if let data = WeightTracker.mr_findFirst(with: NSPredicate(format: "date == %@", dateFormator.string(from: Date()))) as? WeightTracker { let myOutput: AnyObject? = UserDefaults.standard.object(forKey: "height") as AnyObject var sum = (myOutput as! NSString).doubleValue / 1000 let total1 = sum * sum let total = Double(Int(data.weight!)!) / total1 let dye = total/100.00 bmiLabel.text = String(dye) } } }
The sum should only be calculated for the third condition. What is the proper way to handle this?
if let myOutput = UserDefaults.standard.string(forKey: "height") as? NSString , let weight = data?.weight {
let dateFormator = DateFormatter()
dateFormator.dateFormat = "dd.MM.yyyy"
if let data = WeightTracker.mr_findFirst(with: NSPredicate(format: "date == %@", dateFormator.string(from: Date()))) as? WeightTracker{
var sum = myOutput.doubleValue / 1000
let total1 = sum * sum
let total = Double(Int(weight)!) / total1
let dye = total/100.00
bmiLabel.text = String(dye)
}
} else {
bmiLabel.text = "--"
}
Why don't you go the other way around
if myOutput != nil && data?.weight != nil {
// Your logic here
}
else {
bmiLabel.text = "--"
}
Or maybe replacing if
with if-let
altogether to provide safe unwrapping and to get rid of optional chaining and/or force unwrapping
if let myOutput = myOutput, let weight = data?.weight {
// Your logic here
}
else {
bmiLabel.text = "--"
}
Or if you want to provide early escape , then you can even use guard-let
guard let myOutputUnwrapped = myOutput, let weight = data?.weight else {
bmiLabel.text = "--"
return
}
/* Your logic here */
The advantages of if-let
and guard-let
is that you already get an unwrapped value to work with so you don't have to worry about !
and ?
with variables.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.