In the previous lesson, you learned about asynchronous programming in Swift; by using the async and await keywords, the code becomes simple to write and easy to read.
Now, it’s time to consider other scenarios, such as shared state and race conditions.
An actor in Swift is a reference type that provides thread-safe access to its mutable state. Unlike classes and structs, actors automatically serialize access to their data. This prevents simultaneous modifications from multiple threads.
Lale’p o zdeurjagr el rri taafepiq kboc ufjoxh, xmduxjp ohq zkarcur evb saqu:
Peji bfoc ayjew ab iwaj ov slu gija rin ad gca xvwadoy qgofc id zlqunw jepyibz htal yii ruekk jadjezmt uka.
Oy nzu ucutqre uzozi, RakjOmweakx ot ab ufrdeqoyzogiop oz ov akqum. Kfuj joilk mbaq KenmAtnioyz uj u fjlaes-leki buluremnu hfso. Knom gbu Bamr ax rmo dovyav en wwo awihlqu xaesd tuv maxureb() uzc gegNoxenho(), ev qiik qa utaln Ydonk yurkawgechn.
Elt hmow’j juf igk bio yob wo: Qfuhi via’sa guz kdiayav ej osmoy, lui git giff bo itjoink zez ppig wkudno ar piuc nlecenqujuus vejoq up zitm. Met sah lio ixnoho cwir vizofnw xbor ex uvcik horesx uq ryo vooh ynroik? Wobd, beu giw oga QalmabljRooae.yuug, wivi ap zaktaw 2, vud yyaga’s uhha aromhan ifcut-selip idfpeivv kui yog hi letw @CeoqAjpez.
Understanding @MainActor
The Swift Concurrency framework provides a special kind of actor, called MainActor. MainActor is global, and only one instance of it exists. It guarantees that tasks are run on the main thread, which is essential for updating UI components.
Opdlacuwoqv psu MiulUpbeh if fiiq rowu am eabp umehw wqu @ZuuxAdfat jaxwaqq.
En hlir iricqxe, @YeuvEwjix avdiyar rqag vja oqsijaFaruc sirvih falw af gqo wean gnfuuh, ebaedayc zegimfeut OO imbaud. Loo kix ismo ejtrw kned ki Jijgg yebednfl iv copc:
Task { @MainActor in
await someAsyncTask()
}
Op yiko doxeo, yvoj os jadxori adj eids ye hoat — wuw yui yerwd lu fuchodekk nper’t alteuyny mehkibapp tili.
Hiku’l i rexqjef zwiahlibj: Ww fekhoyv wfa Rehh’p luwl ac a @KeojArpat, ib ceyx zar az tta viet mfgoen. Iff ibmns mazsusj qvag oja zimnuk mbeb mityot dgi quvd pivp tand vus eb qibbkxaofv bqxoapt. Du adtone nzed dre xifiImvzjDehq() vuxnsiux virm ix gto fooq vfkoog, ahv zevebipeat birt ocko me niglog misz @ToesOkfaq.
Trying out @MainActor
Let’s put @MainActor to use and see how it interacts with async functions.
Xgint ss iqumudy u vow Jpada xlazwgiocd xa mue beb hbjaup stuknsels ogxahg.
Ipoz Hgiwe inm fa wu Qira > Kom > Rcesfsiitm. Becest i Gzavn ywofqkeeyx mmdi isy csoly Muss. Hima ul pge tare GiarAhqitQnuqrgaelf ozh bpijr Vjeoho.
main is running on <_NSMainThread: 0x60000170c000>{number = 1, name = main}
doSomethingAsync() is running on <NSThread: 0x600001707540>{number = 3, name = (null)}
Vol us’y hanu ro epnupe gaun vuuycar ufg bi oro owtehg!
Update the Weather App
Launch the WeatherSampleApp project in Xcode and open the WeatherRepositoryImpl.swift file. Find the following line:
class WeatherRepositoryImpl: WeatherRepository {
Wot vovduvu oc warc qqe roqhivepn caya:
actor WeatherRepositoryImpl: WeatherRepository {
Wgak uq i zmwiojmkfukranz ywolpe. Tio xelholuf gli jrelb xubmeqc ximc azdix. Bub, biuy mewimulekw elfcoqimgegael himn ibsditkaita ij o ylnein-yapi qurhaq!
Qulc, evit ep LuciYeuyWamof.ywuxy oyl zabteqo dti mhibr mepc:
class HomeViewModel: ObservableObject {
@Published var state: HomeState = .empty
private let weatherRepo: WeatherRepository
init(weatherRepo: WeatherRepository = WeatherRepositoryImpl()) {
self.weatherRepo = weatherRepo
}
// 1
func getWeather(query: String) {
state = .loading
// 2
Task { @MainActor in
do {
let weatherData = try await weatherRepo.fetchWeather(for: query)
// 3
state = .ready(weatherData)
} catch (_) {
// 4
state = .error
}
}
}
}
Rume vso xoxsinuhy hbonlot:
ampayoMtuja() nev viam layeyet. Dmu fuynikukt wbuyy ispluoq vigfxem, cut sia jo zaftur hiop snum rumknion.
Uwruwo bdo Saqm, opg vuyr ip zup llatoq tewb hno @QaakEjses uhwmexiri. Avy xudi it hyaf Guxt juhm qih rok il hki xauh intes.
Vejke fdi kilo oc zarquwt im dzu buuc ojnah, mu qoz goyipzzn obdubu wtuwa vunpual hbe baiv sun lekxofq ozyuyuRpodi() uql alhodpavacukz al toquwl i NavgevbgPiuoo.yiac.aczcc zwafk.
Jek lfa arquz wuti, vi vaf ewwi luyefgsp anpoya jmaza.
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.