默认参数值错误:“实例成员不能在类型viewcontroller上使用”

时间:2015-10-01 09:28:18

标签: ios uiviewcontroller uitextfield swift2

在我的视图控制器中:

class FoodAddViewController: UIViewController, UIPickerViewDataSource, UITextFieldDelegate, UIPickerViewDelegate {

    let TAG = "FoodAddViewController"

    // Retreive the managedObjectContext from AppDelegate
    let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext

    @IBOutlet weak var foodName: UITextField!

    @IBOutlet weak var foodPortion: UITextField!

    @IBOutlet weak var foodCalories: UITextField!

    @IBOutlet weak var foodUnit: UILabel!

    @IBOutlet weak var unitPicker: UIPickerView!

    @IBOutlet weak var unitPickerViewContainer: UIVisualEffectView!

    /*
        unrelated code has been ommited
    */
    func validateAllTextFields(textFields: [UITextField] = [foodName as UITextField, foodPortion, foodCalories]) -> Bool {

        var result = true
        for textField in textFields {
            result = validateTextField(textField) && result
        }
        return result
    }

    func validateTextField(textField: UITextField) -> Bool{
        let correctColor = UIColor.redColor().CGColor, normalColor = UIColor.blackColor().CGColor
        var correct = true

        if textField == foodPortion || textField == foodCalories{
            if !Misc.isInteger(textField.text!){
                correct = false
            }
        }
        if textField.text!.isEmpty {
            correct = false
        }

        textField.layer.borderColor = correct ? normalColor : correctColor

        return correct
    }
}

我有一些文本字段,并且我的validateTextField可以一次验证一个,并且我希望我的validateAllTextFields能够通过逐个检查来验证文本字段的给定列表,如果没有给出列表,我想要检查包含所有三个文本字段的给定默认列表。

我想象的代码如下:

func validateAllTextFields(textFields: [UITextField] = [foodName as UITextField, foodPortion, foodCalories]) -> Bool {

    var result = true
    for textField in textFields {
        result = validateTextField(textField) && result
    }
    return result
}

然而,Xcode给出了错误:

  

实例成员不能用于类型viewcontroller

原因是什么以及如何解决?

1 个答案:

答案 0 :(得分:2)

您不能在函数声明中使用实例变量。使用textFields数组调用该函数并传递参数。

func validateAllTextFields(textFields: [UITextField] ) -> Bool {

    var result = true
    for textField in textFields {
        result = validateTextField(textField) && result
    }
    return result
}
有些人在你班上:

validateAllTextFields(textFields: [foodName, foodPortion, foodCalories])

或者,如果textFields为空,则检查函数内部,而不是使用实例变量

func validateAllTextFields(textFields: [UITextField] ) -> Bool {
    if textFields.count == 0 {
        textFields = [foodName, foodPortion, foodCalories]
    }
    var result = true
    for textField in textFields {
        result = validateTextField(textField) && result
    }
    return result
}