Reputation: 281
I was doing some research on Alamofire and I came across this block of code:
switch encodingResult {
case .Success(let upload, _, _):
upload.responseJSON { response in
if let info = response.result.value as? Dictionary<String, AnyObject> {
if let links = info["links"] as? Dictionary<String, AnyObject> {
if let imgLink = links["image_link"] as? String {
print("LINK: \(imgLink)")
}
}
}
} case .Failure(let error):
print(error)
}
May I know what does _, _ means?
I have seen uses of it like let _ = "xyz"
but i have never seen it used like the code above before.
Does it mean that it has 2 parameters that are not being used?
Thanks in advance
Upvotes: 1
Views: 370
Reputation: 13750
This switch statement is switching over the cases of an Enum. The leading dot in .Success
tells you that Success
is one of the cases of whatever Enum this is.
Swift Enums allow you to use associated values (not to be confused with associated values of Protocols) which let the cases of an Enum store data. The example the Swift docs give is of a Barcode Enum that encodes a standard bar code and a QR code:
enum Barcode {
case UPCA(Int, Int, Int, Int)
case QRCode(String)
}
This says that UPCA bar codes are given four Int values and QR codes are given a single String value, which can be read to and written from. For instance, var productBarcode = Barcode.UPCA(8, 85909, 51226, 3)
creates an object of type Barcode
with value .UPCA(8, 85909, 51226, 3)
; you don't need the full name of the Enum (just the leading dot) because the type can be inferred by the compiler.
When switching over the cases of an Enum, you may assign the associated type values of the matching case to variables and then use those variables in the block for that case.
switch productBarcode {
case let .UPCA(numberSystem, manufacturer, product, check):
print("UPC-A: \(numberSystem), \(manufacturer), \(product), \(check).")
case let .QRCode(productCode):
print("QR code: \(productCode).")
}
If productBarcode
is case .UPCA
, then it matches the first case and those variables are assigned accordingly, and similarly if it is case .QRCode
.
An underscore in the variable assignment list simply tells Swift to discard the value there instead of assigning it to a variable. In the case of your code, it is only assigning the first of the three associated type values to a constant named upload
.
Upvotes: 0
Reputation: 467
Yes it basically means that they are unused values, it is describe here in Apples documentation.
Wildcard Pattern
A wildcard pattern matches and ignores any value and consists of an underscore (_). Use a wildcard pattern when you don’t care about the values being matched against. For example, the following code iterates through the closed range 1...3, ignoring the current value of the range on each iteration of the loop:
for _ in 1...3 { // Do something three times. }
Upvotes: 8