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 Result1enum NetworkError: Error {2 case invalidURL3 case noData4 case decodingError5}6 // Returns either a String or a NetworkError7func fetchData(from urlString: String) -> Result<String, NetworkError> { // Without the https:// prefix: invalidURL8 guard urlString.starts(with: "https://") else {9 return .failure(.invalidURL)10 } // 10 characters or fewer (e.g. only "https://"): noData11 guard urlString.count > 10 else {12 return .failure(.noData)13 } // Both checks passed: success with the data14 return .success("Data from \(urlString)")15}16 17let result = fetchData(from: "https://api.example.com")// Pattern matching extracts the associated value of each case18switch result {// Prints Data from https://api.example.com19case .success(let data): print(data)// Not reached here; would print e.g. Error: noData20case .failure(let error): print("Error: \(error)")21}Output
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.× 11:× 9"× 8{× 5}× 5/× 4>× 3\× 2