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 String
2 case success(String)
// failure carries an Int code and a String message
3 case failure(Int, String)
4}
5
6func describe(_ r: Result) {
7 switch r {
// let msg binds the associated value of success
8 case .success(let msg):
9 print("OK: \(msg)")
// Binds both values of failure, in order
10 case .failure(let code, let msg):
11 print("Error \(code): \(msg)")
12 }
13}
14
// The type is known, so .success is enough: prints OK: Done
15describe(.success("Done"))
// Prints Error 404: Not Found
16describe(.failure(404, "Not Found"))

Output

OK: Done
Error 404: Not Found
Practice typing this code

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

More Swift examples at level 4

← Swift typing practice