默认参数值错误:“实例成员不能用于typesviewcontroller”
在我的视图控制器中:
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可以validation一次,我希望我的validateAllTextFields能够通过检查一个一个,如果列表中没有给出,以validation给出的文本列表,我想检查一个给出包含全部三个文本字段的默认列表。
我想像的代码是这样的:
func validateAllTextFields(textFields: [UITextField] = [foodName as UITextField, foodPortion, foodCalories]) -> Bool { var result = true for textField in textFields { result = validateTextField(textField) && result } return result }
但是,Xcode提供了一个错误:
实例成员不能在typesviewcontroller上使用
什么原因以及如何解决?
你不能在函数声明中使用实例variables。 用你的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为空,并且使用实例variables,则检查函数的内部
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 }