Result Type in Swift
Level 5418 keystrokes
fetchData returns a Result<String, NetworkError> instead of throwing: .success with data or .failure with an error. The URL starts with https://, so switch takes the success branch and prints Got: Data from https://api.example.com.
Swift code
// The failure type of Result must conform to Error1enum NetworkError: Error { // Several cases declared on one line2 case invalidURL, noData, decodingFailed3}4 // Result<Success, Failure> holds either a value or an error5func fetchData(from url: String) -> Result<String, NetworkError> {6 guard url.hasPrefix("https://") else { // Returns the error as a value instead of throwing it7 return .failure(.invalidURL)8 } // Success case with the data string9 return .success("Data from \(url)")10}11 // The URL starts with https://, so the result is .success12let result = fetchData(from: "https://api.example.com")13 // switch must handle both outcomes14switch result {15case .success(let data): // Prints Got: Data from https://api.example.com16 print("Got: \(data)")17case .failure(let error): // Would print e.g. Error: invalidURL (not reached here)18 print("Error: \(error)")19}Output
Got: Data from https://api.example.com
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.
(× 12)× 12"× 10:× 9.× 8{× 4}× 4/× 4,× 3\× 3