Xcode пропускает оператор if else - PullRequest
0 голосов
/ 06 августа 2020
Оператор

my if else проверяет, пусты ли некоторые текстовые поля, и если да, то выдает предупреждение. Однако xcode, даже если проходит все, переходит к другим функциям.

Существует оператор if, который проверяет значение сегментированного элемента управления и, соответственно, проверяет некоторые текстовые поля.

@IBAction func calc(_ sender: Any) {
    
    // Check if dilution text field is empty
    let dilutiontext = self.dilution.text
    if (dilutiontext?.isEmpty ?? true) {
        Alert.showAlert(on: self, with: "Empty Fields", message: "Dilution field is empty")
    }
    if choose.selectedSegmentIndex == 0 {
        
        if (self.number1.text?.isEmpty) ?? true || self.number2.text?.isEmpty ?? true || self.number3.text?.isEmpty ?? true || self.number4.text?.isEmpty ?? true {
            Alert.showAlert(on: self, with: "Empty Fields", message: "Number 1-4 fields should not be empty")
        } else {
            performSegue(withIdentifier: "turner", sender: self)
        }
    } else {
        if (self.number1.text?.isEmpty) ?? true || self.number2.text?.isEmpty ?? true || self.number3.text?.isEmpty ?? true || self.number4.text?.isEmpty ?? true || self.number5.text?.isEmpty ?? true || self.number6.text?.isEmpty ?? true || self.number7.text?.isEmpty ?? true || self.number8.text?.isEmpty ?? true {
            Alert.showAlert(on: self, with: "Empty Fields", message: "Number 1-8 fields should not be empty")
        } else {
            performSegue(withIdentifier: "turner", sender: self)
        }
    }
    
}

I есть еще один файл alert.swift, который управляет предупреждениями:

import Foundation
import UIKit

struct Alert {
    public static func showAlert(on vc: UIViewController, with title: String, message: String) {
        let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
        vc.present(alert, animated: true)
    }
}

EDIT:

Ранее self.dilution.text? .isEmpty, а теперь пусть dilutiontext = self.dilution.text с dilutiontext? isEmpty

Я закомментировал функцию подготовки к переходу, и, к удивлению, предупреждения начали работать. Мне все еще нужна эта функция, и предупреждения работают. Вот функция:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    
    var vc = segue.destination as! SecondViewController
    
    if choose.selectedSegmentIndex == 0 {
        vc.n1 = Int(number1.text!)!
        vc.n2 = Int(number2.text!)!
        vc.n3 = Int(number3.text!)!
        vc.n4 = Int(number4.text!)!
        vc.dil = Int(dilution.text!)!
        vc.cn = Int(choose.selectedSegmentIndex)

    } else {
        vc.n1 = Int(number1.text!)!
        vc.n2 = Int(number2.text!)!
        vc.n3 = Int(number3.text!)!
        vc.n4 = Int(number4.text!)!
        vc.n5 = Int(number5.text!)!
        vc.n6 = Int(number6.text!)!
        vc.n7 = Int(number7.text!)!
        vc.n8 = Int(number8.text!)!
        vc.cn = Int(choose.selectedSegmentIndex)
        vc.dil = Int(dilution.text!)!
    }

}

Когда я запускаю его, вместо отображения предупреждений (которые проверяют, пусто ли текстовое поле), он переходит к функции перехода и отображает Неожиданно найденный ноль при разворачивании необязательного значения , что ожидается

Ответы [ 2 ]

0 голосов
/ 07 августа 2020

Очевидно, что предупреждения пропускались, если одно из условий if в функции перехода было истинным. Так что, если бы было что-то, что изначально сделало бы утверждения ложными, а затем после прохождения предупреждений оно сделало бы их истинными, проблема была бы решена.

Поэтому я сделал еще две функции для каждой if и if else операторы в segue fun c.

func option1() -> Bool {
    if (self.number1.text?.isEmpty) ?? true || self.number2.text?.isEmpty ?? true || self.number3.text?.isEmpty ?? true || self.number4.text?.isEmpty ?? true || self.dilution.text?.isEmpty ?? true || !(self.number5.text?.isEmpty ?? true) || !(self.number6.text?.isEmpty ?? true) || !(self.number7.text?.isEmpty ?? true) || !(self.number8.text?.isEmpty ?? true) {
        return false
    } else {
        return true
    }
}

func option2() -> Bool {
    if (self.number1.text?.isEmpty) ?? true || self.number2.text?.isEmpty ?? true || self.number3.text?.isEmpty ?? true || self.number4.text?.isEmpty ?? true || self.number5.text?.isEmpty ?? true || self.number6.text?.isEmpty ?? true || self.number7.text?.isEmpty ?? true || self.number8.text?.isEmpty ?? true || self.dilution.text?.isEmpty ?? true {
        return false
    } else {
        return true
    }
}

, которые проверяют, были ли все условия истинными, и если да, то возвращают true, чтобы программа могла перейти к segue fun c.

Segue будет проверять, были ли условия истинными, если нет, он будет go с помощью предупреждений, поэтому опция option1 () или option2 () вернет true - и, следовательно, условия if в segue fun c будет верно для продолжения программы.

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    
    var vc = segue.destination as! SecondViewController

    if option1() == true {
        vc.n1 = Int(number1.text!)!
        vc.n2 = Int(number2.text!)!
        vc.n3 = Int(number3.text!)!
        vc.n4 = Int(number4.text!)!
        vc.dil = Int(dilution.text!)!
        vc.cn = Int(choose.selectedSegmentIndex)

    } else if option2() == true {
        vc.n1 = Int(number1.text!)!
        vc.n2 = Int(number2.text!)!
        vc.n3 = Int(number3.text!)!
        vc.n4 = Int(number4.text!)!
        vc.n5 = Int(number5.text!)!
        vc.n6 = Int(number6.text!)!
        vc.n7 = Int(number7.text!)!
        vc.n8 = Int(number8.text!)!
        vc.cn = Int(choose.selectedSegmentIndex)
        vc.dil = Int(dilution.text!)!
    }

}
0 голосов
/ 06 августа 2020

Очевидно, что ни условие «if», ни условие «else if» тогда не верны. Добавьте

let dilutiontext = self.dilution.text
let celltext = self.cell.text

, затем установите точку останова и проверьте значения.

...