守卫放开后强制展开

Force unwrap after guard let

有人告诉我我的代码包含大量强制展开。如果我确定操作的值不会为零,我认为这样做是可以的:

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
    }

好看吗?如果没有,应该怎么办?

建议避免过度使用 force-unwrapping optional 变量。

即使您确定,代码也可能会在您之前可能没有预料到的某些特殊情况下生成 nil 值。这将导致您的应用不必要地崩溃并带来糟糕的用户体验。

尝试使用 Optional Binding if-let / guard-let 语句来安全地解包您的选项。

@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
}