Result Type in Swift

Level 5496 keystrokes

fetchData checks the URL with two guard statements and returns a Result: .failure with a NetworkError or .success with the data. The URL passes both checks, so it prints Data from https://api.example.com.

Swift code

// Error type for the failure side of Result
1enum NetworkError: Error {
2 case invalidURL
3 case noData
4 case decodingError
5}
6
// Returns either a String or a NetworkError
7func fetchData(from urlString: String) -> Result<String, NetworkError> {
// Without the https:// prefix: invalidURL
8 guard urlString.starts(with: "https://") else {
9 return .failure(.invalidURL)
10 }
// 10 characters or fewer (e.g. only "https://"): noData
11 guard urlString.count > 10 else {
12 return .failure(.noData)
13 }
// Both checks passed: success with the data
14 return .success("Data from \(urlString)")
15}
16
17let result = fetchData(from: "https://api.example.com")
// Pattern matching extracts the associated value of each case
18switch result {
// Prints Data from https://api.example.com
19case .success(let data): print(data)
// Not reached here; would print e.g. Error: noData
20case .failure(let error): print("Error: \(error)")
21}

Output

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
  • .× 11
  • :× 9
  • "× 8
  • {× 5
  • }× 5
  • /× 4
  • >× 3
  • \× 2

More Swift examples at level 5

← Swift typing practice