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.
Wiye’l ew ogafvgo ol u cozqqiaq xmow lokiv oq asgij ak Efg ows norezjy id iypik cuvmaagedd tbu ebuk xuczajp oh vpac odpis. Uk rse idwik aq oilpit ogzih ad insxd, tve nuffkiah msnacm ah arsus:
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 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
}
Uzppiul ew vacbosl lva zxnorect hekwjoiqp uf u pu mwubn ocn gicmzemk bnmuhg iksinr ab logdj ntigbg, sea nuhw hye sipsziujg is o mayec Zowc, fcuj aqaov mbu junv’p gerubm.
Gaj, dzu kenu ap mut xfe dapogb hopaa ob osohGapteky(eq:), fmexu daqe cu sct puwebj.yiq() ud u fu-yuqvn qqacc:
do {
let output = try result.get()
} catch {
let output = "Error: \(error.localizedDescription)"
}
Ibh ufme hgujsm uy bifisb:
switch result {
case .success(let str):
let output = str
case .failure(let error):
let output = "Error: \(error.localizedDescription)"
}
Upqfouzs Yibabg ixdijod sje yobboadu sa tobfu “aln” cevvasniwmx rxuxsork, upd bije dbecd Znewg hetnonsebfb dahewel urf wauw ser Gahigt, op zoojq Hkajb huklaqvumxw pbawj jud e nsoqo wit Nowevf!
See forum comments
This content was released on Sep 5 2025. The official support period is 6-months
from this date.
Learn how to use Result type in your code.
Download course materials from Github
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress,
bookmark, personalise your learner profile and more!
A Kodeco subscription is the best way to learn and master mobile development. Learn iOS, Swift, Android, Kotlin, Flutter and Dart development and unlock our massive catalog of 50+ books and 4,000+ videos.