what’s the difference between while using `let` in switch case at begin or in the()

i0S Swift Issue

Question or problem in the Swift programming language:

I have a little doubt about the let position in switch case, here is a simple code, which one is better

enum Result{
    case success(code:Int)
    case fail(err:NSError)

var result = Result.success(code: 3)

switch result {
case  .success(let code):// first
case let .success(code)://second

How to solve the problem:

Solution 1:

case .success(let code):

This syntax is used when the enum specifies the let value. In this case, enum Result specifies that the case success will also include an Int value for code.

Using let right after case in a switch statement is generally used in conjunction with a where clause to allow for more complex case values in a switch statement. An example of such could be as below

var text = "Hello"
var greetings = ["Hello", "Good Bye"]

switch text {
case let value where greetings.contains(value):

Solution 2:

As The Swift Programming Language: Enumeration: Associated Values says:

You can check the different barcode types using a switch statement, similar to the example in Matching Enumeration Values with a Switch Statement. This time, however, the associated values are extracted as part of the switch statement. You extract each associated value as a constant (with the let prefix) or a variable (with the var prefix) for use within the switch case’s body:
switch productBarcode {
case .upc(let numberSystem, let manufacturer, let product, let check):
print(“UPC: \(numberSystem), \(manufacturer), \(product), \(check).”)
case .qrCode(let productCode):
print(“QR code: \(productCode).”)
// Prints “QR code: ABCDEFGHIJKLMNOP.”

If all of the associated values for an enumeration case are extracted as constants, or if all are extracted as variables, you can place a single var or let annotation before the case name, for brevity:
switch productBarcode {
case let .upc(numberSystem, manufacturer, product, check):
print(“UPC : \(numberSystem), \(manufacturer), \(product), \(check).”)
case let .qrCode(productCode):
print(“QR code: \(productCode).”)
// Prints “QR code: ABCDEFGHIJKLMNOP.”

In short, they’re equivalent, and the latter is a useful shorthand when you are extracting more than one associated value.

Solution 3:

case .success(let code):// first
case let .success(code)://second

In the examples as you have shown them, there is no difference. Both are legal, and both do the same thing. They are equivalent patterns in this context.

Hope this helps!