Enum Associated Values in Swift
Level 4281 keystrokes
The cases of Result carry different data: success holds a message, failure holds a code and a message. describe uses switch to extract them and prints OK: Done and Error 404: Not Found.
Swift code
1enum Result { // success carries one String2 case success(String) // failure carries an Int code and a String message3 case failure(Int, String)4}5 6func describe(_ r: Result) {7 switch r { // let msg binds the associated value of success8 case .success(let msg):9 print("OK: \(msg)") // Binds both values of failure, in order10 case .failure(let code, let msg):11 print("Error \(code): \(msg)")12 }13}14 // The type is known, so .success is enough: prints OK: Done15describe(.success("Done"))// Prints Error 404: Not Found16describe(.failure(404, "Not Found"))Output
OK: Done Error 404: Not Found
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this Swift code and how often they appear.
(× 14)× 14"× 8:× 5.× 4,× 3{× 3}× 3\× 3_× 1