There is such a code. And for some reason, the guard instruction does not work.

struct User { var firstName: String var lastName: String var age: String } let firstNameTextField = UITextField() let lastNameTextField = UITextField() let ageTextField = UITextField() firstNameTextField.text = "Александр" lastNameTextField.text = "Иванов" ageTextField.text = nil func createUser() -> User? { guard let firstNameUnwrap = firstNameTextField.text else { return nil } guard let lastNameUnwrap = lastNameTextField.text else { return nil } guard let ageUnwrap = ageTextField.text else { return nil } return User(firstName: firstNameUnwrap, lastName: lastNameUnwrap, age: ageUnwrap) } if let userNew = createUser() { print(userNew.firstName, userNew.lastName, userNew.age) } 

Prints - "Alexander Ivanov"

Tell me, please, why the guard does not work? After all, it must interrupt the execution of the code, because ageTextField.text = nil. Those. nothing should be printed.

    2 answers 2

    For UITextField there is no difference between nil and the empty string.
    Hence ageTextField.text = nil = ageTextField.text = ""

    Therefore we have:

     firstNameTextField.text = "Александр" lastNameTextField.text = "Иванов" ageTextField.text = "" 

    More information about processing empty lines can be found here .

    • Thank! And for the hint, and for the article. Is it then correct to say that the compilers of the task did not correctly compile it, since they did not take into account this circumstance. Or did I incorrectly solve it? - maxMas
    • Sorry, what is the main goal? If you write a guard that would interrupt the code, then no. (+ I do not see the point; I would not want to crash my application on every blank line) If I write code that will work even for an empty call, but it will return an empty string - yes. You can add extra. check for a completely empty user, or finish handler and return something in the style of * age is not specified *, but this is in my humble opinion. - Serhii S.
    • The goal is to solve the problem, it is purely educational, there is a guard theme, it is necessary to implement it in a specific context. And here it turns out to be such an ambush. - maxMas
    • and by the way, if for UITextField there is no difference between nil and the empty string, then how to be with guard? After all, it turns out that in this example, it does not respond to either nil or the empty string. - maxMas

    This is how you can do the test:

     textField.text = nil print("textField.text: \(textField.text)") 

    After launching you will receive:

     textField.text: Optional("") 

    Those. TextField always returns an Optional ("") instead of nil.