Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

swift

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
    print("success",code)
default:
    print("fail")
}
like image 817
zhj Avatar asked Jun 11 '19 02:06

zhj


1 Answers

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.

like image 152
Rob Avatar answered Nov 30 '22 06:11

Rob