Search code examples
swiftxcodeoption-typeguard

guard let found nil


I am new to guard let patterns. How come my app crashes when selectedRooms.text is nil instead of doing the return part? And why is rooms of optional type when I know that numberOfRooms is not nil?

guard let numberOfRooms = selectedRooms.text else {
    return selectedRooms.placeholder = "type something"
    }
let rooms = Int(numberOfRooms)
x = Int(ceil(sqrt(Double(rooms!)))) //found nil value

Solution

  • selectedRooms.text cannot return nil.

    A UITextField and UITextView always returns a String value. An empty String ("") is returned if there is no text in the UITextField and UITextView. That's the reason else part is not executing and rooms value is nil.

    Now, in the below statement you're force-unwrapping(!) the rooms.

    x = Int(ceil(sqrt(Double(rooms!))))
    

    But, since the rooms is nil, so forcefully unwrapping it is throwing runtime exception.

    Solution:

    You need to add an empty check as well for the else part to take effect, i.e.

    guard let numberOfRooms = selectedRooms.text, !numberOfRooms.isEmpty else { //here...
        return selectedRooms.placeholder = "type something"
    }