Enum with Associated Values in Swift
Level 3230 keystrokes
Defines a Result enum whose cases carry a String, then uses switch to extract that value. The value is a success, so it prints Got: Hello.
Swift code
// Each case can carry its own associated value1enum Result { // success carries a String labeled data2 case success(data: String) // failure carries a String labeled error3 case failure(error: String)4}5 // Creates a success value holding "Hello"6let result = Result.success(data: "Hello")// switch must cover every case of the enum7switch result {// Matches success and binds its value to data: prints Got: Hello8case .success(let data): print("Got: \(data)")// Would run for a failure value (not reached here)9case .failure(let error): print("Error: \(error)")10}Output
Got: Hello
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.
(× 9)× 9:× 7"× 6.× 3{× 2}× 2\× 2=× 1