我有三个条件:
data.weight
和myoutput
均为nil
myoutput
没有价值 data.weight
和myoutput
都有一个值
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)
}
}
}
仅应针对第三个条件计算总和。处理此问题的正确方法是什么?
答案 0 :(得分:1)
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 = "--"
}
答案 1 :(得分:1)
你为什么不走相反的路
if myOutput != nil && data?.weight != nil {
// Your logic here
}
else {
bmiLabel.text = "--"
}
或者也可以将if
完全替换为if-let
,以提供安全的拆包并摆脱可选的链条和/或强制拆包 >
if let myOutput = myOutput, let weight = data?.weight {
// Your logic here
}
else {
bmiLabel.text = "--"
}
或者,如果您想提供早期逃生,那么您甚至可以使用guard-let
guard let myOutputUnwrapped = myOutput, let weight = data?.weight else {
bmiLabel.text = "--"
return
}
/* Your logic here */
if-let
和guard-let
的优点是您已经获得了可使用的未包装值,因此您不必担心变量中的!
和?