&安培;&安培;运算符在Swift3中不起作用

时间:2017-09-18 04:52:43

标签: swift binary-operators

我正在使用Objective-C TextFieldValidator(https://github.com/dhawaldawar/TextFieldValidator)自定义类来验证我的应用中的文本字段,它具有验证正则表达式的功能:

 -(BOOL)validate{
    if(isMandatory){
        if([self.text length]==0){
            [self showErrorIconForMsg:strLengthValidationMsg];
            return NO;
        }
    }
    for (int i=0; i<[arrRegx count]; i++) {
        NSDictionary *dic=[arrRegx objectAtIndex:i];
        if([dic objectForKey:@"confirm"]){
            TextFieldValidator *txtConfirm=[dic objectForKey:@"confirm"];
            if(![txtConfirm.text isEqualToString:self.text]){
                [self showErrorIconForMsg:[dic objectForKey:@"msg"]];
                return NO;
            }
        }else if(![[dic objectForKey:@"regx"] isEqualToString:@""] && [self.text length]!=0 && ![self validateString:self.text withRegex:[dic objectForKey:@"regx"]]){
            [self showErrorIconForMsg:[dic objectForKey:@"msg"]];
            return NO;
        }
    }
    self.rightView=nil;

    return YES;
}

现在在我的UIViewController中,我使用以下if语句验证我的寄存器窗体中从此自定义TextFieldValidator继承的所有文本字段:

tfFirstName.isMandatory = true
tfLastName.isMandatory = true

if (tfFirstName.validate() && tfLastName.validate()){
   return true
}else{
   return false
}

tfLastName字段为空,但似乎if语句仅调用tfFirstName.validate()并始终返回true {{1}运营商不在这里工作。 在Objective-C&amp;&amp;工作得很好,但在Swift 3中却没有。为什么&&运算符不在此处工作以及解决方案是什么?

3 个答案:

答案 0 :(得分:0)

当text为nil时,validate()函数返回YES。在swift中,UITextfield.text可以生成nil值。将验证功能的第一部分更改为......

    if(isMandatory){
        if(self.text == nil || [self.text length]==0){
            [self showErrorIconForMsg:strLengthValidationMsg];
            return NO;
        }
    }

答案 1 :(得分:-1)

我通过修改我的代码解决了我的问题,如下所示:

let isValidFirstName = tfFirstName.validate()
let isValidLastName = tfLastName.validate()
if (isValidFirstName && isValidLastName)){
   return true
}else{
   return false
}

答案 2 :(得分:-1)

请检查您的代码,&amp;&amp;正在按预期工作..

func validate(_ textfield:UITextField) -> Bool{
    if textfield.text?.characters.count == 0{
        return false
    }else{
        return true
    }
}

func testValidate(){

    let tfFirstName = UITextField()
    tfFirstName.text = "fhgghh"

    let tfLastName = UITextField()
    tfLastName.text = ""

if (validate(tfFirstName) && validate(tfLastName)){
        NSLog("true")
    }else{
        NSLog("false")
    }
}

testValidate()

控制台:: 2017-09-18 11:54:08.796 MyPlayground2 [22908:2591237] false