检查许多空参数?

时间:2016-04-08 12:26:05

标签: swift

我有代码来检查一个空参数:

if let isEmpty = name?.isEmpty where isEmpty == false {

但是我需要实现代码来检查是否有很多错误?例如数量和价格以及名称...我将如何使用此代码获得此信息?

if let isEmpty = name?.isEmpty where isEmpty == false {
    if let isEmpty = total?.isEmpty where isEmpty == false {
        if let isEmpty = price?.isEmpty where isEmpty == false {
           if let isEmpty = quantity?.isEmpty where isEmpty == false {
            }
        }
    }
}

当我列出它们时,当我在循环结束时执行try catch循环时,它不起作用。

@IBAction func saveItems(sender: AnyObject) {
    let name = txtName.text
    let total = txtTotal.text
    let price = txtPrice.text
    let quantity = stepperValue.text

    if let isEmpty = name?.isEmpty || 
          isEmpty = price?.isEmpty || 
          isEmpty = total?.isEmpty || 
          isEmpty = quantity?.isEmpty where isEmpty == false {

    }

    // Create Entity
    let entity = NSEntityDescription.entityForName("Item", inManagedObjectContext: self.managedObjectContext)

    // Initialize Record
    let record = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: self.managedObjectContext)

    // Populate Record
    record.setValue(txtName, forKey: "name")
    record.setValue(txtTotal, forKey: "total")
    record.setValue(txtPrice, forKey: "price")
    record.setValue(stepperValue, forKey: "quantity")
    record.setValue(NSDate(), forKey: "date")

    do {
        // Save Record
        try record.managedObjectContext?.save()

        // Dismiss View Controller
        dismissViewControllerAnimated(true, completion: nil)

    } 
    catch {
        let saveError = error as NSError
        print("\(saveError), \(saveError.userInfo)")

        // Show Alert View
        showAlertWithTitle(title: "Warning", message: "Your message could not be saved", cancelButtonTitle: "OK")
    }

} 
else {
    // Show Alert View
    showAlertWithTitle("Warning", message: "Your to-do needs a name.", cancelButtonTitle: "OK")
}

3 个答案:

答案 0 :(得分:1)

一个解决方案是一个很大的(但是单一的,没有嵌套),复杂的if语句:

if let name = name, total = total, price = price, quantity = quantity
    where !name.isEmpty && !total.isEmpty && !price.isEmpty && !quantity.isEmpty {

    // use name, total, price, quantity

}

另一个可以说是更好的解决方案是逐步打开它们,每个变量使用guard语句逐步打开它们。

guard let name = name where !name.isEmpty else {
    // name is nil or empty
    return
}

guard let total = total where !total.isEmpty else {
    // total is nil or empty
    return
}

guard let price = price where !price.isEmpty else {
    // price is nil or empty
    return
}

guard let quantity = quantity where !quantity.isEmpty else {
    // quantity is nil or empty
    return
}

// use name, total, price, and quantity, all are non-nil, non-empty

当然,取决于你做的是零还是空的情况,第一个解决方案可能更好用guard编写:

guard let name = name, total = total, price = price, quantity = quantity
    where !name.isEmpty && !total.isEmpty && !price.isEmpty && !quantity.isEmpty else {

    // something was nil or empty
    return

}

// use name, total, price, quantity

如果我正在编写此代码,假设nil或空表示无法将数据保存到数据库的状态,我会选择两种guard方法中的一种,我选择的将取决于我想要消息给用户的描述性。

答案 1 :(得分:0)

您可以创建自己的isEmpty函数,该函数接受可选的String,如果字符串为nil或空,则返回true。然后,要立即检查多个,您可以创建一个您尝试检查的字符串数组,并将其过滤为空。

let arr = [name, total, price, quantity]

let isEmpty = { (string: String?) -> Bool in
    guard let string = string where !string.isEmpty else { return true }
    return false
}

// if none of the strings are empty
if arr.filter(isEmpty).isEmpty {
    // do stuff
}

您还可以将自己的any功能作为ArraySequenceType上的扩展名,这可能比过滤更好。

答案 2 :(得分:-1)

required_params = array('name','price',..)//all the keys required.
input_params = array('name'=>'abc', 'price'=>20,...)//input array in which conditions are to be checked.
foreach(required_params as $key_required){
  if(input_params[$key_required] is empty?)
    return false;
// if you dont have input_params array and have variables. just check
//${$key_required} is empty
  .....
}