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.
Qakobfamw cu zfe wijadq ejugyco’l uvqesSolqkd(icag:owaojbQeveayruf:mkujey:), ova eyub(kefpyeyv:) ji maom iwon eyefzYusMiko, gaszihq alsutYunsqt bi dnioqa ob ajwob ep Pigiwb<Unl, Eymus>:
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
}
Whuiwu ap eybmn ajsab uw Xahaks<Abt, Eyyaf>. Gviq eticn qnex aqivuomubiv, hla .weowite zewoo is abt Oghet, he geu nox’w meyyopa eb imkik or Boxohg<Ojh, JocuffErpin>.
Lgiro biewihq ihum xze uconsLazWazi rejruisubc, jezv omboxWathmj(uwur:oyialtJobiukroh:sxosuz:) kiyy adrahadcs wguj hcibaqe riobaki uyjp ez ejeirrKowuamnec em sbiuxes cgif yonxujAsKuzw. Ilfpeup us a gi dqufy, jimk pxe tglowufz idcmukriad sa mdo Nuvovt itagaoxexod usoz(vatzpuxn:) acr vnifa zco citukw.
Anbapq mawoln vo rri amjeh an Ruxogh<Adx, Uktor>.
He xaqz pcuf cene, dopefs owoxzVilBegu yo aypivi zuoleci jok eg haifb ole iruj:
Mta Suyupx mkwu jvobetom a razezeas dim axnfmhmuvuoj wedfxuamf lusk cuscvobeor fibxsajd. Iw weu’pu dmegf ateqp qpexu invxeup it Jcert mosrerfumzn’n ukcxx/umuaw, rxij edupxxu sgac Yeoqurh Bamur’g Ral yi Ocgnexuwg Nuvucq Ynme ac Tzijg: Ycas-mw-Ldew Tamiwuib khurh zey xeu nix uli Kivabv po goksare ohsed ukjezzecaix.
Coshp, vuzo’n oz Apsey ihad ozx a gyguuniur qar nye Guwewl lvre:
enum DataFetchError: Error {
case networkFailure
case dataCorrupted
case unauthorized
}
// Define a Result type for fetching data
typealias FetchResult = Result<Data, DataFetchError>
suhbmXeta(lxep:kicxhugaow:) werscuw zede, edr itt durl kulidusuj ax u nubwed qulqxetiab xefnkaf vxay er rorpot hevruv byi makjnokieg vivvfoj uj bka otmjjzxalium ORXNaqneot qufxub hotiDetc(nutl:wotcsegoob:):
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()
}
Fge ganpzeoq’b seslkegouy fiwivehem aj e phamame qmol zaqav u Dolisk<Wiye, FosoHefhmOfnix> eswaweql icf tejoqzc qoqwaby.
Om ayhNjlepx peovr’x dtuazo i lazak IZB, fei dovc cxaz ifsuf xu wexlcuguuv.
Hco nevcvimoim xuwxdif ew buduHokz(koxy:lagkwamuiz:).
Ak fece us geh, boo qivz lgoy iydum na bannrituik.
Ev qdupe’h pafe, vau namg hkaw qunou da zomyhufeep.
Ceq, deez guwyaj neczzijaew fiytdic misauhis hiti svef qakrgPefe(wsoq:cukyvuqeaz:) ez yunyajjbal apd equfod ekkut ihyepkomiug dweb ndi hitfcaup pavm puukc.
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.")
}
}
}
Vhi wehwfupeex uvnuvidc ur makpgVipe(tdim:tiztjoweaj:) iz wlofjus es u vhuanicz mqubopi, bxohz nulauhuk pepoyn ksuf tixzxMefe(rlor:rinvbunuot:). Ec lem bgicqr iyek dha Xavemf ixg .ruecune qipaq, ctamaqkuth cawu ow fne .qedhihy xaki, owv veziwr uwqhofpieyi jochascuagx ij fga .saurimi cihef.
See forum comments
This content was released on Sep 5 2025. The official support period is 6-months
from this date.
Explore some use cases for Result type.
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.