swiftoption-typeswift-optionals

Force unwrap after guard let


I was told my code contains a lot of force unwrapping. I thought it's okay to do that if I am sure that the value operated won't be nil:

private var x: Int?
private var y: Int?

@IBAction func startButtonPressed(_ sender: UIButton) {
    
    guard let numberOfRooms = selectedRooms.text, !numberOfRooms.isEmpty else {
        return selectedRooms.placeholder = "type it, dude"
    } 
    let rooms = Int(numberOfRooms)
                   
    x = Int(ceil(sqrt(Double(rooms!))))
    y = x //grab some values from user input
    maze = MazeGenerator(x!, y!) //generate a maze 
    hp = 2 * (x! * y!) //get hp value depending on user input
    
    currentX = getRandomX(x!) //get random value in 0...x
    currentY = getRandomY(y!)
    currentCell = maze?.maze[currentX!][currentY!] //game starts in a random part of the maze
                            
    refreshButtons() //refresh UI
    maze!.display() //print maze scheme in debug console
    }

Does it look fine? If not, what should be done?


Solution

  • It is recommended to avoid over using the force-unwrapping the optional variables.

    Even if you're sure, the code might generate nil values in some corner cases that you might have not expected earlier. This will then result in unnecessarily crashing your app and giving a bad user experience.

    Try using Optional Binding if-let / guard-let statement to unwrap your optionals safely.

    @IBAction func startButtonPressed(_ sender: UIButton) {
        
        guard let numberOfRooms = selectedRooms.text, !numberOfRooms.isEmpty, let rooms = Double(numberOfRooms) else {
            return selectedRooms.placeholder = "type it, dude"
        }
        
        self.x = Int(ceil(sqrt(rooms)))
        self.y = x //grab some values from user input
        
        guard let x = self.x, let y = self.y else {
            return
        }
        
        maze = MazeGenerator(x, y)
        hp = 2 * (x * y)
        
        //for rest of the code I need to know the declaration of currentX, currentY, maze variables
    }