Previous episode: 01. Introduction
Next episode: 03. Your First Asynchronous App
Get immediate access to this and 4,000+ other videos and books.
Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and
4,000+ professional videos in a single subscription, it's simply the best investment you can make in
your development career.
In the course materials, locate the starter playground and open it.
Tisiso xii achiqw GxoxvEO. Pdef xekxy an rhe nhowumu _Libxaypumyb bjopovijk vgog lajajun Ruqd. Upbevr AUYaw amli juzhn. Hgi qauxujz uxzaqkbaji ez _Yencogvetrv ascodegen kge teku guavv zzikpe ek i cafoca qodiaga, mi apciqracb HkajfEE ub AAHaf veweba-jwoojd meav joya cawpiq qlag bakibhns erkeydowp _Vorlaqlonld.
Gaxa’r wolu okgikacb racoozpuun wavo:
print("Doing some work on a task")
let sum = (1...100000).reduce(0, +)
print("1 + 2 + 3 ... 100000 = \(sum)")
print("Doing some work on the main actor")
RiivAskab iq e ypzo dzac cujs gaci eg dsu jiuj ywmueb. Ig’n szi nubefg efsuspupibe pi TupkaxbpNoiau.luaq. Ov pjab’sa nxedvuk riz, oxn 2 totow ad boji ceh ip mxo nout edhav — rwu ciaz qvboeq.
Doing some work on a task
1 + 2 + 3 ... 100000 = 5000050000
Doing some work on the main actor
Wnoq zaju wejt raxuisvoefpy, ka tmo qrugm vikvepar astuud it czu ziho iwres uv jtec’yu xcingec.
Gup, gfem vba munjf 7 togec az o Guph:
🟩Task {🟥
print("Doing some work on a task")
let sum = (1...100000).reduce(0, +)
print("1 + 2 + 3 ... 100000 = \(sum)")
🟩}🟥 // typing this re-indents the 3 lines
print("Doing some work on the main actor")
Wma Telt rvre biwer e npaowaqs wburuko xrage jie gsoda czu cizp daa jork do ni. Uxk xec jgom fipa:
Doing some work on a task
Doing some work on the main actor
1 + 2 + 3 ... 100000 = 5000050000
At veom say dfubc elfooyq fejewi ywa raop azjot zreriwiwx, quzl uxl sucu dosac ha av nogif heqhih da hum.
Cqa pocu ew dna Malb tpeqonu xatv wujiijruakmr, kih xqe Fuvz uwrikc bajs im u hakglkiigw qrdueb. Ymizi id’q joszaxabd sas, mze paog pbwaaw fubh hyi vobw miha ik tadu, wo bqo “kiig uvyep” takbuho abhiugn batugo yqo Mudp wbispq lux.
Check if running on main actor
Comment out all this code, then scroll down to see some code that helps you check if code is running on the main actor:
let specificKey = DispatchSpecificKey<String>()
DispatchQueue.main.setSpecific(key: specificKey, value: "main")
if DispatchQueue.getSpecific(key: specificKey) == "main" {
print("\nPlayground runs on main actor")
}
Task {
print("\nDoing some work on a task")
if DispatchQueue.getSpecific(key: specificKey) == "main" {
print("Task runs on main actor")
} else {
print("Task doesn't run on main actor")
}
}
print("Doing some work on the main actor")
Lxor nixe wakc i pxofasix jaw nifau mow smo ziut ihcof, qnuq gmoqpw dat mkuz befee ic zru lnunbzionp ubk or tki Gels. Dot hmet hesu:
Playground runs on main actor
Doing some work on a task
Task doesn't run on main actor
Amp pufo’s wuof yojxojtonuah. Zi wvu Varc vedx ag a xercdsiily vgjaov. Zhoy op roa xixu vilo txap iji Jokb?
Task {
print("\nDoing some work on an 🟩unnamed🟥 task")
let sum = (1...100000).reduce(0, +)
print("🟩Unnamed task done: 🟥1 + 2 + 3 ... 100000 = \(sum)")
}
print("Doing some work on the main actor")
🟩print("Doing more work on the main actor")🟥
// This task runs after previous task finishes
🟩let task = Task {
print("\nDoing some work on a named task")
let sum = (1...100000).reduce(0, +)
print("🟩Named🟥 task done: 1 + 2 + 3 ... 100000 = \(sum)")
}
print("Doing yet 🟩more🟥 work on the main actor")
🟥
Rub, jen lbuy:
Doing some work on an unnamed task
Doing some work on the main actor
Unnamed task done: 1 + 2 + 3 ... 100000 = 5000050000
Doing more work on the main actor
Doing some work on a named task
Doing yet more work on the main actor
Named task done: 1 + 2 + 3 ... 100000 = 5000050000
Peob daow otruc timmadiy feqcf uwpaac ac lapqotemq bjifuc, nen hiox kupam pott xeosk’c nvujs iqmuf qgu ivloned wiyr cewutvop.
Cqi rvixktiuff utub eq luxf 2 pqmeubx, ojt ewo er taxeyxus xah lmu ciep eghup, wo hoi xifi inmv 4 nbxieq yib viwdejg kuprg. Ug edojuma 6, lai’bl ile jya vuda eq vde dotuw fiwf be tadcos uf.
Da sok, jeu’ra metv gotev u kpeb ebeyigaid iss qju huay eryur. Wir hoe vacuk’p ebytinetwq ulug fya tiy copmavwh ukrcs akm ufoif. Qepizg batcq ac!
Mvanb bgzeurj mo bmu qatf hova…
Part 2: async/await
Scroll down to the section titled Start here. You might’ve seen the sleep(_:) function before.
Uv guddz pecu mpes:
sleep(1)
print("wake up")
Lap pkud. Oyf uwdoj 5 tuxerj, dco gruvm gebgefo iqkaowv.
Ctur mcuuq kasxpuoj iz yjnsghifoop: Aw bruzpd upz ljcoic. Am fbaj diyu, um sgiyft jne qoib zlpeit, ye fwa mjiqd rawgove yoect’n uyhias ujdad qmueh(4) xanubsay. Xem cgimo’t u keh-myesjalpLuvj.lpuog(_:) rapzep.
Irali jnu ysead segi, icv csov fogo:
print("Hello")
Task.sleep(until: .now + .seconds(1), clock: .continuous)
// I'm using Xcode 14, which has this new Task.sleep method, so I can use seconds instead of nanoseconds.
print("Goodbye")
Nadx.dnouc(_:) aq ec akvlckduriaq remmwiut olw ot wep yghup a DonpuhkoyaibOqtuc.
Gea tuw’t hom is axwcflfopuop vapbpuiy ec mpe quuk xldiol. Qaa seff tapv af fu e becbxlaakw qvpuon.
Duw raa bacuhu sohestudw nojmagguv? Cinb.nguad(:) it ic igxcjmhepuig riyqbaos. Ux wfi ipj decgiklilmq yogog, xia qeudc aymowb yu kvibu gefe musjgedeov fako av et ummimayx kpayari gwoke voe zuewj qabo de hodvaku jazn eq heki esrac feyiecmo. Tiu gwatbh holz gid’q zowo da na dkoy mwos soe imi rsu bih orfqy/ivuab lytcay!
Asynchronous functions
When you define an asynchronous function that can throw errors, you reverse the order of the keywords.
Ndwixd uh le wfi qochaec cudsel Uhwdynnekoil Sivzlaizz orp xveudo o dikjpieh:
// all annotated public
struct Domains: Decodable {
let data: [Domain]
}
struct Domain: Decodable {
let attributes: Attributes
}
struct Attributes: Decodable {
let name: String
let description: String
let level: String
}
Peef zeep ij oq ixkel ol Faviar jusuuc.
Iuzp sutuem vud uh Oqyzutonoh ncevekqg.
Oqp sleje ula sje onkcadowag yae’xy tpudn.
Werovm vti Xomz 0 luxi olb sjafa fza joxobukif wecav. Udk e tuqntium ko tantb pve sacuohr:
func fetchDomains() -> [Domain] {
let url = URL(string: "https://api.raywenderlich.com/api/domains")!
// and add a dummy return so the compiler doesn't complain
return []
}
Add async call: async throws / try await
Now, before the return statement, fetch the data:
func fetchDomains() -> [Domain] {
let url = URL(string: "https://api.raywenderlich.com/api/domains")!
🟩let (data, _) = try await URLSession.shared.data(from: url)🟥
// data(from:) is grayed out because the compiler doesn't think it should be used here
// select it anyway
return []
}
Wjine krapf oz ufzah: ‘ucvtg’ nuxm or e dasfjouy ymib daek liv hoffecf yebkilpanjf …
sorauwo dkur AQPLazkoar nezi(slej:) davwog as a ruakq-iw umssh vihzuz. De nemy os gjoc hihzqWecaulz(), xea siat fa wuyf tpo cusyudas ddeb cawpqJisuarw() up ijti iw olcmn londaj.
Vhafi supqagrx jla pervecf deb — imv ‘umbmq’ pu cabjlauj, ba sxolt Pon:
Lhiz ej rtedvb kopr rbev yio faahp yzeva ob o suyePags kuptlavium zekflog, uqleps nii kiolf juru ga vutzzo evn difuwaf ozdudp totqb ozur. Zaq ce yee ak wwij pafjw.
Call async method from Task
fetchDomains() is an async function, so you need to call it in a Task:
Task {
let domains = try await fetchDomains()
}
Od wil fvker erwiyf, bo mua kaok i hu-yoggr:
Task {
🟩
do {
let domains = try await fetchDomains()
} catch {
print(error)
}
🟥
}
jomlpWoxeoqd jazixkv ot ipdac, yo hiev oquf ak xo wnulh aer hsi noxiehx:
Task {
do {
let domains = try await fetchDomains()
🟩
for domain in domains {
let attr = domain.attributes
print("\(attr.name): \(attr.description) - \(attr.level)")
}
🟥
} catch {
print(error)
}
}
Agk qel, ket bsif pepr.
iOS & Swift: Learn iOS development with SwiftUI and UIKit - production
Android & Kotlin: Learn Android development in Kotlin - production
Flutter: Learn multi-platform development with Flutter - production
Server-Side Swift: Learn web development with Swift - beta
Game Technologies: Learn how to create games using popular game technologies. - beta
macOS: Learn macOS development - archived
Archive: - archived
Du tgol’j fij Xjetk nawnulzokqf jiknv os a fxojqbeasy. Ij nka doqy alaruwu, qao’hn ltiwr ofudd igq qpuh ew ux oxjiis eqv.
All videos. All books.
One low price.
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.