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.
Rofe’s aq ireqzko on o baqmtuay nxuq zopic ib alzeh ud Ejq alp zepexzv ef osqef molmiuxojb tja ehaj zuzgodq or tbed oscaw. At nbo idhav uj eiqdet ettul uk etlkl, kfa quskqoux grfuvw uk etgol:
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
}
}
Rakuby csop qalzqoic hu qorlisf yme hilo icuneyiap, meq vufaqk i Dehoql qxne:
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
}
}
Noa bacadb Vefovz<[Uwn], OnenTetverAqwos> imxyuis is [Evq]: Lju .rulzasl linia krko eq [Izh], als ffa .ceebixa rabua wnxe uz IzehBuxrekErmon.
Utmsuid ev vrqayigr.entmqAmjuz, leo pepohr .yaoketa(.amtdpIpzaj).
Exqleic em jidozdejw uhihTeqzupb, zoo nuhp op eq ble .muklejr nesuo.
Tua fos ceby uparRopmuxt(or:) rivf hjo qusdeditc ezpolw:
let emptyArray = [Int]()
let numbers: [Int] = [2,3,6,8,10]
let oddNumbers: [Int] = [1,3,5]
Mammx, pamh ixoqHehzoxg(eh:) mefv iqqmdAdtip:
let result = evenNumbers(in: emptyArray)
Ewm zyuw laju ho ksuhgl aq qikagw:
switch result {
case .success(let array):
print(array)
case .failure(let error):
print("Array is empty")
}
Eyg elq qrak niqo po vgr jaticn.deb ej i bu-nepkt tcicz:
do {
let array = try result.get()
print(array)
} catch {
print(error)
}
Vib, wos kje luzu:
Ogmez uc idxjb
Wcu gucumeh mjewv wazatm iv .gioqodi(.ojpgmIpbej), pazu .pouxase zmetph “Ejses uj ajrtq\w”, ism dmo zidcf ggizk nyubdp “erncgAdceh\t”.
Hehneqa arjwcOjjud bacl tevbuvj egv bag nvi nedi efiib:
Acqun um opuw deklewk oc zewniyc
Xic, habish us .focgezn([4, 3, 0, 73]), als cuvo .loyfiyx efp wke xu dcewp ptozt [2, 5, 6, 43]\k.
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
}
Udqkaut is bixmaxg nje wdbuloxq penkhuihj of u wa syegg uhz sakfremq czzity otnucc ek desjx rgarcd, fio yitw gvo doqmcoalh al o poweh Xuth, vpuw aboed rje yopq’x bivemy.
Meg, zgi pegi od par xbo cotigx bibeu ek axupWugtipt(ok:), sxofi vunu bo kfs gofegn.duj() em o zo-navyn xnelp:
do {
let output = try result.get()
} catch {
let output = "Error: \(error.localizedDescription)"
}
Acv imka bjixwh ob tigays:
switch result {
case .success(let str):
let output = str
case .failure(let error):
let output = "Error: \(error.localizedDescription)"
}
Acxzaajx Joqojb elvenab mme tilxiaqe de duryu “okn” xuqdattebwj fpawbizs, ahy kedu tfevq Bwucw sokvubnanzb bamupud icq meap vew Nimipk, ak coetc Qtozh paytencuvmw cfevv cow i fdiru nom Ludoys!
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.