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

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):
    print("Yes")
default:
    print("No")
}

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.

Tags:

Swift