Use Cases

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

In the Lesson03-Result-Type playground, click Next to open the Lesson03-Result-b page.

Convert Throwing Expression to Result

Result has a nifty initializer init(catching:) to convert any throwing expression to a Result. You can use this to collect results while looping over a collection.

let bakery = Bakery()
var results = [Result<Int, Error>]()  // 1

for (key, value) in bakery.itemsForSale {
  let result = Result {  // 2 
    try bakery.orderPastry(
      item: key,
      amountRequested: 1,
      flavor: value.flavor)
  }
  results.append(result)  // 3
}
let itemsForSale = [
  "Cookie": Pastry(flavor: "ChocolateChip", numberOnHand: 20),
  "PopTart": Pastry(flavor: "WildBerry", numberOnHand: 0),  // guarantee error
  "Donut" : Pastry(flavor: "Sprinkles", numberOnHand: 24),
  "HandPie": Pastry(flavor: "Cherry", numberOnHand: 6)
]
Results array
Vorikmp annot

Completion Handlers

Click Next to open the Lesson03-Result-c page.

enum DataFetchError: Error {
  case networkFailure
  case dataCorrupted
  case unauthorized
}

// Define a Result type for fetching data
typealias FetchResult = Result<Data, DataFetchError>
func fetchData(
  from urlString: String,
  completion: @escaping @Sendable (FetchResult) -> Void) {  // 1
  guard let url = URL(string: urlString) else {
    completion(.failure(.networkFailure))  // 2
    return
  }

  // Simulate fetching data
  URLSession.shared.dataTask(with: url) { data, response, error in  // 3
    guard let data = data else {
      completion(.failure(.dataCorrupted))  // 4
      return
    }
    completion(.success(data))  // 5
  }.resume()
}
fetchData(from: "https://example.com") { result in
  switch result {
  case .success(let data):
    print("Successfully fetched \(data.count) bytes.")
  case .failure(let error):
    switch error {
    case .networkFailure:
      print("Network failure - Please check your connection.")
    case .dataCorrupted:
      print("Data corrupted - Unable to process the data received.")
    case .unauthorized:
      print("Unauthorized - Access denied.")
    }
  }
}
See forum comments
Download course materials from Github
Previous: Result Type Next: Conclusion