0

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

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
    }

看起来不错吗?如果没有,应该怎么做?

4

1 回答 1

3

建议避免过度使用强制解包变量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
}
于 2020-08-31T08:39:22.860 回答