&& operator doesn't work in Swift3

305 views Asked by At

I am using Objective-C TextFieldValidator(https://github.com/dhawaldawar/TextFieldValidator) custom class for validating textfields in my app, which have a function which validates regex on it:

 -(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;
}

Now in my UIViewController I am using the following if statement to validate all my textfields inherited from this custom TextFieldValidator in my register form:

tfFirstName.isMandatory = true
tfLastName.isMandatory = true

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

tfLastName field is blank, but it seems like if statement calls only tfFirstName.validate() and always return true, i.e. && operator is not working here. In Objective-C && works fine, but in Swift 3 it's not. Why is the && operator not working here and what's the solution?

3

There are 3 answers

0
Carien van Zyl On

When text is nil, your validate() function returns YES. In swift, UITextfield.text can produce a nil value. Change the first part of your validate function to something like...

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

I fix my problem by modifying my code as follows:

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

Please review your code, && is working as expected..

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()

console:: 2017-09-18 11:54:08.796 MyPlayground2[22908:2591237] false