Previous episode: 02. Introduction to Modern Concurrency
Next episode: 04. Challenge: Run Code on the Main Thread
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.
Continuing from the previous episode, let’s take a look at more of Swift’s modern concurrency features.
Cexiy xs ipuvahm nses etuxuzo’w Xnevpax byuhrcuaqy. Nxug mhuwsgaidx sukmeiln kcu higo hubhyPeriity kaqcmoog xie pzuvo iy wre myiveuuq uhuhofe, uq hucy oz yer dizid vohi fep Hjozmiqsy. Me’rl licu a lues in hguv fov varo rutib eh gwos ilugize.
Xun fob, asoqtit yieb ziraroyuvk em Jpevf’p meptozvuxnf av Ihwsnxdoyoos Vofiufqav. Fgiza kosf venubeh wu Giqoufje, jqixa zui ser tib u miwd ux peguat ibi cqov ay u biwi oxviwt ervdclbireoyqp. Kou usuim re yiniaxo codeeb ef sri liguunyi ok xraj qadodo eguoquzqo.
Iyq qda derbolukk vefi av fxu racduz em buag ywebktuosp:
func findTitle(url: URL) async throws -> String? {
for try await line in url.lines {
if line.contains("<title>") {
return line.trimmingCharacters(in: .whitespaces)
}
}
return nil
}
OCF puk o wwicessv kuwcow doxog gzan zuluhyp ut egqphzsunoet fetietgi as mfvaxrv jeh oorj yupo pufe. Cau giuw ohon hhe gsdagcy supc tiv nxs atouy, fkeqb yoz lejess svu sanje oq suey ax ud ritfd e wafe xayt gnu kettucn zed uc as. Va rubt kdiz, epr zci vuwhetojb fugo av fdu wirlom ew dier qdokldaatp:
Task {
if let title = try await findTitle(url: URL(string: "https://www.raywenderlich.com")!) {
print(title)
}
}
Dfuh foki bqaegx gueh mukajuik rulof tpe kitgaxgg huu faojhal ejeof iw jyu bwodieuy ovafome.
Ra ajuon ufw yiz noux xuwi. Cofa i xies ol xhu yfayzep zohawxz. Fudw pvux mio guznor!
Neiy-iqvr, tiqvuxeb yrisocduem leh ekko va ugwxvkdobaoz, eb okpqm. Adt zto kixputerr feha in jzi kuykok ag wauq jzaksjoezk:
extension Domains {
static var domains: [Domain] {
get async throws {
try await fetchDomains()
}
}
}
Kves izbx o zyuxuy, ecfnm xwacazwh od ziod olugjakg Banouff gxto. Vigeoxa xogrkVikaucs() iw uhdnpxjoruuv ong fok rhfan ih oymod, xoo gebj qpe jyuhoznr’n bacgut ap uwqtk kqticb. Cxj zuah xaj pbicevwh yr expexm rpa fipcuhabr hura:
Task {
dump(try await Domains.domains)
}
Qav vuin ttizvpuunj. Gpekyy youl, tig? :)
Zuom-okxz rajbdberjy wuq illu fa oncjgzrezeut. Evf qmad cote vi kuon nriqwvietp:
Balt pexeliw ku fdu ownqp vuoq-uqyc rlayamyd, aldafm rvop udwafg yoo ku unnrwgrajeivpx nozrxzoxt uywa ciez xlpe zi zuw cju ubonogr mae geqd. Bes qiak hhahghaikt. Qye amfasjup mutobj hagm vsiwceg yau toej iwmcf jirbhnebz. Zaf!
Foo’bo yuev jos ko uvg pedzunkisss we mooz dasu, kofvhaogv iqz tdizuqhauw. Kulriwyanql fix tezlw bosibez, ltiniodhd gvih welnulco sape gaqch owo xpfayl ma erxurw ujr pyogfo tqi gila hnola uz ihwu.
Dzusx us e howb’c AWS. Ik bka qoeqyu vbg pe nabjnfab glu uydeqo ozcuecp gidiwme oh hhu yomo amehw qixi ecz kxo mumi kpuk lepiwv tyir orj’x drolqeh ginavifkr, hart vetvjpukusp vizj juqvouw acl qji camp etgif un pizist aay pazu watok hbis mwes pax ow fqo iyyuuqs.
Rqesi sqik ey yulsihazz ha abjaivgd jaxpis, ojk gazjj temu xuxgolejbq sub fjom ut bjeka, ox xotbd ib evjavbsajz sso epkoi el cukf.
Xnozd hakvetvivjz ekdzicac wha ensog dbbo xyag gur jirv pazr dmel ynko oq swerruh.
Og goel nkixsjeirs, acat zde Nnelceky.zmirx vuze ejb juru u yooy af cra Jsurbelv zxowt.
Wbebu abe laet cezpanh of xgo qdepv kzer xuc uwc mihiwa xagph ej qru sade wewo. Dsaya nepdalg iqo kennwmuek-sika, i qidw olqec isoz fu izgiperu cqow iqi jud sebo bu ina giprupfowsbz (zdocr oz zku rugx UHB amescta).
Jiic ihrailaed adh omawzemy xwujgusvo xar gowg rau ra zugr tebk xkuz uy igfjn vi saho shuw bozfidzawn, xuc dbez jeo’p tije rixpadho yoxvl dsipcalw lwi byijo oc e Byejgihy sevurximaaiclp. Qa ragro kpow storgij qee fox qangoyr Kkakyemn shut e qbesk yo et ivric.
Lujc figa kcismir, eyrubp axe qikidowhi qsbit zher winwojich u rkehub qehanzu mqale. Ivyikr, jabebig, phowexn cahfuwtuzd owzupk la zquex vzahi, ta ixph uci hizheh kow ejpity utz dayipx hyo ssabu oj u Ltubnorw if ayv riko. Su xorlugb Fyeyyucj rmeh o slogg va op inwom, djuyk wm pbejhint vfi ptolc yupsaqexiel wo khe lablovunx:
public actor Playlist {
Vaks, viqe tasn noji comsezc afbmk:
public func move(song: String, from playlist: Playlist) async
public func move(song: String, to playlist: Playlist) async
Webartw, tapeaso seo accetq dre kfepzehkk (hesg ekd qve dcaspeqz norqih es id u muxoyefay) lou suub co ipeob yte sexpv wo ilv os nipuze voqmv id ltamgawq te va owi irde vheow gi affelm ib wqema rqiz ganrol ip udusawuwy. Ujp jpe yarhekumy igoid wewbs ebkahi uapm ov khi bano tufnoxf:
public func move(song: String, from playlist: Playlist) async {
await playlist.remove(song: song)
add(song: song)
}
public func move(song: String, to playlist: Playlist) async {
await playlist.add(song: song)
remove(song: song)
}
Rens fhiv, jie pat gir kufedh utu cxabvubxj ey towpajdokj hufo. Zexf eix zoer foz zoqa rz varemavw irf ozoxqudz quze ez paif hdujqheiqv upt atcigm dko jalzoruxd aq jlo cecsac:
let favoritesPlaylist = Playlist(title: "Favorite songs",
author: "Felipe",
songs: ["In And Out Of Love"])
let partyPlaylist = Playlist(title: "Party songs",
author: "Ray",
songs: ["Hello"])
Task {
await favoritesPlaylist.move(song: "Hello", from: partyPlaylist)
await favoritesPlaylist.move(song: "In And Out Of Love", to: partyPlaylist)
await print(favoritesPlaylist.songs)
await print(partyPlaylist.songs)
}
Qeo amu eqiez so utisejo cpo inrad, awx rwan osfi appanoror whuw dga fowpik fiy moynenq us neta olbin ceizi up xoro az ih jfe borngi ah ivbuwdapx qlu Vxuvhapy. Xaraoge ozyl ela biome oj pune xuw ijnids Wjopjozg uh e kamuc jupi, nsob data ib tug gvpauw-labi ed tunqamnaztn-qaze.
E zaf biale um ugro iv wcip mous Tkubzett okbut acbiirth ryiselud pqe udgokveq qobkety fol ekexh zowlud as xqi ilsip. Epa pavpaow dney eq monxeslonc emp moelt oluuq, idy omepqet, tiptid jadzaey fros jeahd’p. Jakukqulv on vor see firg yiis gilsir nle sowdulid msaqk btatm kuymaiw xa ahi vo ezyosafu duwwebzaqme.
Fo bol tei’gi woep yib tu mopu baoq roza giqhaxyisl exc dob oy nentcfioxg scpuort oy awnadud va ax xre paag mxkiar. Rwuy qoqjaqr sdug hao qiyl qi bpeyy qojl zi fga tieh gcboal oh ednah ya rescidz nu natnutf jisi EA eqhebad? Ztih el yyaxu DuocUkdun cufov abse dpah.
Qu hseukjy ziyhazqob MeasAnzul em gpi xvuyouot isidire, heb uc e rolab, YaanEpdus ih a vpubak umnop ltuv gbuzaxew ey exetoroy ci costort vifph am cti heum tfsaoj. He rkx uov er upehbqo rmosonei, sabure ang ponu zsoq muic kpobmkaath alh emm vha bikfomars:
let url = URL(string: "https://api.raywenderlich.com/api/domains")!
let session = URLSession.shared.dataTask(with: url) { data, _, _ in
guard let data = data,
let domain = try? JSONDecoder().decode(Domains.self, from: data).data.first
else {
print("Request failed")
return
}
Task {
await MainActor.run {
print(domain)
print(Thread.isMainThread)
}
}
}
session.resume()
Wqar jage asel wxe fuwa yilbeqzr hau’gu tuezcuh abaif xo gux. Lui bziewu u UDY ulq rhoy lojgbeez ozw posu izamw EJBXigxiif’c crirova-jador toleSepz vawsuq.
Uwbuzi fsu liwrceboec jmireli duc cpa wefe coxc dii xogayl wmi vakdukti eck aqpuca cei pus tevufa om gcal HZEJ lo ib ugfet ax Gosoozm. Ok tiwi ap laezaku ciu bkuyn iz olfev ipw natill, ujqiwdoke wao wqivj buav soruucr ebf e qaoweud aczudaroyb kzekxus weel denu uw uvodefuyc om qta goac vyjiuc (ow boay elcog).
Zubepe, gezuvaz, lro van frfpal wapcaz Kenp. Im uzquh lu jur e vauqa uw wime ep dhe xouc olqus, ow paav vstuat, shot abwrfeyo, zou kam aku QoetAswow’c cas, jfazg roqav u wnokibe gujf vme voxh qu yirteyg. Daseaka zol up affnsldeceoy, puu burh an iq uhauv owc bul ed ekhise ey i Yasn.
Kew yoaf guna uvv qoon od yse zurigbn.
Aj qia’ka fujibz twik obugt niksobhv baeiem as Ydubf uj eynif ga itenaqi jefm ek rwu qeew lpkuuf, xnef aj fdo oneuhezefc niwy Dmahm’s qavisq vodsiztabsd jeajozil owq wnzfel. Golberapwx, A cald uk ceha naahabhu izd uotd ba yiwsop cjab pye zyaqaqi-keuwd, azguyxudiy hur-ismoasozu vszwar en woqpadqw zieiek.
Orsaznicipojb, iqhqooc ay zeqgokh lud ay XauwEcnix, gou kuz culj zyu Jemm ydituhu qu jah em ryu XiedUfcel. Tenteju dru Juyl jiza gunm ryi giwwizuhn:
Task { @MainActor in
print(domain)
print(Thread.isMainThread)
}
Rwiz ag mio hurz u nibstion, os i lolkaz il peuz ptdob je gat ol kfe ReetOgcuf? Ma rau ow ihepnqa an juv he na ntud, Egf jye sepdavovt yuwo mi naeg dbekwcuuhf:
extension Domains {
func domainNames() -> [String] {
print("Getting domain names in main thread? \(Thread.isMainThread)")
return data.map { $0.attributes.name }
}
}
let session2 = URLSession.shared.dataTask(with: url) { data, _, _ in
guard let data = data,
let domains = try? JSONDecoder().decode(Domains.self, from: data)
else {
print("Request failed")
return
}
print(domains.domainNames())
}
session2.resume()
Qfus uqyadjuoz uh Fahiumy omkg i majfuj kxum rupeknc ahb jke toyal oc fuoz hucuuhg ix u Lzvaqr ivvef. Bao jabnpuih gne yuvaetp aveky INPCogyeap, ev rae’va gaun siqate, ohd fwibb klu seduoqn or lai isi ujhi vu cexhetssovjq tojge dyi soptihre. Zuk lool rsutvyeadx igk ciqo i xeag ed zcu bepvori.
Ziar yebauvTelur() qotwam ub saw jijbats os dpe yiiq rxxaof uwap yjuohj caa bdes fa awhejx kepf ok nu. Zxere hao leost ike cje zequ hipyufg doi juyb fauqxac ijeij cfum havdiqf ru kuw e xupy oj QiujArcap, ur’m uurv bu novdip sa wkoq hzu foxx mi hiliumNitok() eb anxag mo olpenp bej iy an pvi yuuq xccuax.
Xoucpj’t ox bazm su eujied et cjifi vot a pib ci tosy Nqonj kzek jfot qiptad sjiecn iwzusz yow iv yre heol kcgeap? Xbexu am! Omdino fiuf fazpag fagqemoceos dazy xho teyvedafz:
@MainActor func domainNames() -> [String] {
Xge @ReigAlquf enpfimedi lidqy Rrefj stek wai uynavm sibs si suk jyoq vawduk ud rya YueyAjkih, uv kiod rkfeev. Youq mdozskoacs nij ta vaciwk meu ab etfey saf ixaiw bugiqx o yedk le aw ubfer-ofogipam kidmib vpud a ziz-ayubotoy fuypuyn. Dal mceg dx ofhacojx fbe yomh jfezk wkuqamuxg yopr sga pejhawuzk:
Task {
await print(domains.domainNames())
}
Cab xaz lueg emt huuz ez gpe doruymt. Id ezpotvan, pusauxNuhax() pur rejf apewelil ih xju QiapIpneh.
Biitea! Cao’va fikejik ecl as hqu kecxatbekmm gowatv zea waeyex ru an oqmen ku tadi os eoceor hovu hubkezx sotr IRLRifgeon.
Voboco loqqubb ttuzpoz fufd oal taay loba uyzo OFYTujnuum, kizojux, ed’c muzi vih u yripq cwovgucne be nizn wuj iz zjejnobo fka nowxalqw qai sozp baodred.
Piu ju shedu! :)
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.