Friends, please tell me why it occurs and how to fix the following error. There is code running on swift 1.2 in Xcode 6. When I try to run it in swift 2 in Xcode 7, an error occurs. Here is the code itself - we take the entered values, call the compare function with the given ones, which returns true or false

var passwd=textfield.text var login=loginfield.text let ver = compare(login, b:passwd) if ver == true { label.text="True" } else { label.text="False" } } 

In swift 2, an error occurs on the line:

 let ver = compare(login, b:passwd) "Value of optional type 'String?' not unwrapped; did you mean to use '!' or '?' 

Why and where to dig?

    1 answer 1

    The value that comes out of the text field may be empty, and accordingly contain nil. Therefore, the compiler refers to this value as optional (String?).

    I assume that your function compare takes as a parameter "String", and you submit the type "String?"

    To correct the error, you must either tell the compiler so that if the fields contain nil, replace them with an empty string:

     var passwd=textfield.text ?? "" var login=loginfield.text ?? "" 

    Or change your function so that it takes optional "String?" As a parameter

    • Yes, you are right. Changed the function to "String?", It all worked. Another option was to specify var passwd = textfield.text! var login = loginfield.text! but as I understand it, the less correct way? - Oleg
    • Oleg, with this approach there can be an error "Unexpectedly found nil while unwrapping an optional value" if the fields are empty. - Vladislav Chapaev