Why doesn't work a guard statement?

Hello, I encountered with such a problem. In the code below, the guard statement does not fire.


struct Person {
    var firstName: String
    var lastName: String
    var age: String
}

let firstNameTextField = UITextField()
let lastNameTextField = UITextField()
let ageTextField = UITextField()

firstNameTextField.text = "John"
lastNameTextField.text = "Williams"
ageTextField.text = nil


func createPerson() -> Person? {

    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 Person(firstName: firstNameUnwrap, lastName: lastNameUnwrap, age: ageUnwrap)
}


if let personNew = createPerson() {
    print(personNew.firstName, personNew.lastName, personNew.age)
}

// Print: John Williams



Why the guard statement doesn't work here?

Replies

What do you mean guard does not fire ?


Do you create the textFields in IB ?

If so, why not declare an IBOutlet

@IBOutlet weak var firstNameTextField: UILabel!


Could you also instrument your code with print:


func createPerson() -> Person? {

    guard let firstNameUnwrap = firstNameTextField.text else { print("No firstName"); return nil }
    guard let lastNameUnwrap = lastNameTextField.text else { print("No lastName"); return nil }
    guard let ageUnwrap = ageTextField.text else { print("No age") ; return nil }
    print(firstNameUnwrap, lastNameUnwrap, ageUnwrap)

    return Person(firstName: firstNameUnwrap, lastName: lastNameUnwrap, age: ageUnwrap)
}

"What do you mean guard does not fire ?"


Guard statement should stop the function and return nil because the property ageTextField.text = nil. Therefore, nothing should be printed.


"Do you create the textFields in IB ?"


No, because I take this code from textbook.


"Could you also instrument your code with print:"


I did it, but the result is the same. Now it prints:


// Print:

John Williams

John Williams

So, instrument as I proposed, to see exactly what occurs :


    guard let ageUnwrap = ageTextField.text else { print("No age") ; return nil }


In fact,

even though you set ageTextField.text = nil,

its value is optional("")


Can read this, describing that string may be either nil or optional("") :

h ttps://medium.com/ios-os-x-development/handling-empty-optional-strings-in-swift-ba77ef627d74