variable was written, but never read?

2020-03-01 09:31发布

问题:

Im getting the following warning variable 'isTaken' was written to, but never read on the following code :

func textFieldShouldEndEditing(textField: UITextField) -> Bool {

        var isTaken: Bool = false

        if textField == usernameTxt { var query = PFQuery(className: "_User")
        query = PFQuery(className: "_User")
        query.whereKey("username", equalTo: usernameTxt.text!)
        query.findObjectsInBackgroundWithBlock {
            (objects: [AnyObject]?, error: NSError?) in
            if error == nil {
                if (objects!.count > 0){

                    isTaken = true

                    }
                } else {
                    print("Username is available. ")
                }
            } else {
                print("error")
            }
          }
        }
        return true
    }

why am I getting the warning and how do I do away with it?

回答1:

As error says variable 'isTaken' was written to, but never read means you are creating isTaken instance and assigning a value to it but it never used.



回答2:

Just eliminate the statements:

var isTaken: Bool = false
isTaken = true

Since the value is never used defining and assigning to if accomplishes nothing.



回答3:

Basically it's saying that isTaken is assigned a value, but it doesn't actually do anything in your code. You are never using it or checking it's value, so it's simply an warning saying that the variable is unnecessary.

If you actually are using isTaken and the compiler doesn't realize for some reason, you could probably just add another line right after

isTaken = true;

that just says

isTaken;

Or make isTaken global if you're using somewhere else in the code.



回答4:

Its a compiler warning to point out a dead code. You probably have copy pasted some code and removed some unwanted code. In doing so, usage of local variable isTaken is gone. So, its only being assigned a value and never used for materializing any benefits. You can either simply remove the code around isTaken or double check and put back the functionality around it :).



回答5:

It's warning you about a var that you set a value, but don't operate over it after.

Is very important keep your code clean and safe, so the xcode just gives you a little help with it.

isTaken = true;

Thats the point you set a value to isTaken variable.

Try to review your code and think about the use of this variable.