Home > Software engineering >  Role of underscore "_" in conditional statement (if else) in Swift
Role of underscore "_" in conditional statement (if else) in Swift

Time:09-07

Can somebody please explain the role of "_" in Swift code below.

var guessWasMade: Bool {
    if let _ = game.guesses[currentQuestion] {
        return true
    } else {
        return false
    }
}

I understand how it is usually used as unnamed parameter in for-loops and functions. But could not find any explanation for if else statement.

Tutorial explains it as guessWasMade checks game.guesses for a value. If a value is found we know the user has made a guess at the question.

game.guesses is an array of integers.

This is part of class declaration. Full code looks like this

class GameViewModel: ObservableObject {

  // MARK: - Published properties
  // 2
  @Published private var game = Game()
 
  // MARK: - Internal properties
  // 3
  var currentQuestion: Question {
     game.currentQuestion
  }
  // 4
  var questionProgressText: String {
    "\(game.currentQuestionIndex   1) / \(game.numberOfQuestions)"
  }

// 1
  var guessWasMade: Bool {
       if let _ = game.guesses[currentQuestion] {
           return true
       } else {
           return false
       }
   }

   // MARK: - Internal Methods
   // 2
   func makeGuess(atIndex index: Int) {
       game.makeGuessForCurrentQuestion(atIndex: index)
   }
   // 3
   func displayNextScreen() {
       game.updateGameStatus()
   }
}

CodePudding user response:

If let statements check to see if the value is nil. If it is, then the statement is false. If it isn't, then the value is assigned to a variable.

var optionalValue: Int? = 42

if let nonOptionalValue = optionalValue {
    print(nonOptionalValue) // -> 42
} else {
    print("optionalValue is nil")
}

So, when you do if let _ = game.guesses[...], you are checking to see if game.guesses[...] is nil. If it isn't, then you are ignoring the value with a wildcard pattern (_), which will match anything.

Because you are ignoring the value, it is the same as saying

if game.guesses[...] != nil {
    return true
} else {
    return false
}

Then, because you are simply returning the value of the condition, you can just return the condition itself:

var guessWasMade: Bool {
   game.guesses[currentQuestion] != nil
}
  • Related