如果其他条件正确,如何处理多个?

时间:2019-04-26 11:30:48

标签: swift

我有三个条件:

  1. data.weightmyoutput均为nil
  2. myoutput没有价值
  3. data.weightmyoutput都有一个值

    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)
            }
        }
    }
    

仅应针对第三个条件计算总和。处理此问题的正确方法是什么?

2 个答案:

答案 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-letguard-let的优点是您已经获得了可使用的未包装值,因此您不必担心变量中的!?