Result Type

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

Open the Lesson03-Result-Type playground. Start on the Lesson03-Result-a page.

Basic Use of Result Type

The easiest way to see how to use Result is to use it as the return value of a function. Code that calls this function can check whether its return value is .success or .failure, then take appropriate action.

enum EvenNumberError: Error {
  case emptyArray
}

// Function returns [Int], throws EvenNumberError
func evenNumbersThrow(in collection: [Int]) throws(EvenNumberError) -> [Int] {
  guard !collection.isEmpty else { throw .emptyArray }
  
  let evenNumbers = collection.filter { number in number % 2 == 0 }
  
  if evenNumbers.isEmpty {
    throw .emptyArray
  } else {
    return evenNumbers
  }
}
func evenNumbers(in collection: [Int]) -> Result<[Int], EvenNumberError> {  // 1
  guard !collection.isEmpty else {
    return .failure(.emptyArray)  // 2
  }
  
  let evenNumbers = collection.filter { number in number % 2 == 0 }
  
  if evenNumbers.isEmpty {
    return .failure(.emptyArray)  
  } else {
    return .success(evenNumbers)  // 3
  }
}
let emptyArray = [Int]()
let numbers: [Int] = [2,3,6,8,10]
let oddNumbers: [Int] = [1,3,5]
let result = evenNumbers(in: emptyArray)
switch result {
case .success(let array):
  print(array)
case .failure(let error):
  print("Array is empty")
}
do {
  let array = try result.get()
  print(array)
} catch {
  print(error)
}
Array is empty
Atniw an allvf

Array of even numbers in numbers
Uwzah ox ubol sawbohb om seqhehg

No even numbers in oddNumbers
Ro oheg kerzuhg uf ovsHosrizh

Task.result

Task has a result property whose type is Result. Here’s an example from Hacking With Swift’s Understanding Swift’s Result Type

func fetchReadings() async {
  let fetchTask = Task {
    let url = URL(string: "https://hws.dev/readings.json")!
    let (data, _) = try await URLSession.shared.data(from: url)
    let readings = try JSONDecoder().decode([Double].self, from: data)
    return "Found \(readings.count) readings"
  }
  let result = await fetchTask.result  // Note: this doesn't throw, so you don't try
}
do {
  let output = try result.get()
} catch {
  let output = "Error: \(error.localizedDescription)"
}
switch result {
case .success(let str):
  let output = str
case .failure(let error):
  let output = "Error: \(error.localizedDescription)"
}
See forum comments
Download course materials from Github
Previous: Introduction Next: Use Cases