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 Error
1enum NetworkError: Error {
// Several cases declared on one line
2 case invalidURL, noData, decodingFailed
3}
4
// Result<Success, Failure> holds either a value or an error
5func fetchData(from url: String) -> Result<String, NetworkError> {
6 guard url.hasPrefix("https://") else {
// Returns the error as a value instead of throwing it
7 return .failure(.invalidURL)
8 }
// Success case with the data string
9 return .success("Data from \(url)")
10}
11
// The URL starts with https://, so the result is .success
12let result = fetchData(from: "https://api.example.com")
13
// switch must handle both outcomes
14switch result {
15case .success(let data):
// Prints Got: Data from https://api.example.com
16 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

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

More Swift examples at level 5

← Swift typing practice