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")
}
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 thelet
prefix) or a variable (with thevar
prefix) for use within theswitch
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
orlet
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With