默认参数值错误:“实例成员不能用于类型视图控制器"
在我的视图控制器中:
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能够通过一一检查它们来验证给定的文本字段列表,如果没有给出列表,我想要检查包含所有三个文本字段的给定默认列表.
I have a few textfields, and in my validateTextField can verify one at a time, and I want my validateAllTextFields be able to verify a give list of textfield by checking them one by one, if the list is not given, I want to check a given default list that contains all three textfield.
我想象的代码如下:
func validateAllTextFields(textFields: [UITextField] = [foodName as UITextField, foodPortion, foodCalories]) -> Bool {
var result = true
for textField in textFields {
result = validateTextField(textField) && result
}
return result
}
然而 Xcode 返回一个错误:
However Xcode gives an error back:
实例成员不能用于类型视图控制器
instance member cannot be used on type viewcontroller
原因是什么以及如何解决?
What's the cause and how to fix?
不能在函数声明中使用实例变量.使用 textFields 数组调用该函数并传递参数.
You cannot use instance variables in function declarations. Call the function with your textFields array and pass the parameters.
func validateAllTextFields(textFields: [UITextField] ) -> Bool {
var result = true
for textField in textFields {
result = validateTextField(textField) && result
}
return result
}
有人在你的班上:
validateAllTextFields(textFields: [foodName, foodPortion, foodCalories])
或者你检查你的函数内部是否 textFields 为空而不是你使用实例变量
Or you check inside of your function if textFields is empty and than u use the instance 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
}