Swift introduces Actors in version 5.5 and this is a big change in concurrency at WWDC. The actors main used to manage shared state often leads to Data races and Race conditions problems in a concurrent system. In-sort two pieces of code can’t access an actor’s data at the same time.Actors are like other Swift types as they can also have initializers, methods, properties, and subscripts, while you can also use them with protocols and generics. Furthermore, unlike structs, an actor requires defining initializers when your defined properties require so manually
Some key concepts about actors:
- The actor is a Reference Type
- To access actors’ property we have to put await keyword before calling.
- The actor does not support inheritance but we can implement the protocol.
- An actor automatically serializes all access to its properties and methods, which ensures that only one caller can directly interact with the actor at any given time.
Please click here to know more about Actor.
Let’s create A exemple
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
actor TemperatureLogger { let label: String var measurements: [Int] private(set) var max: Int init(label: String, measurement: Int) { self.label = label self.measurements = [measurement] self.max = measurement } } func callActor() async{ let obj = TemperatureLogger(label: "test", measurement: 10) print( obj.label) print( await obj.max) } |
Note: The above code makes you lose the whole state of your app.
In conclusion, I hope this code will help you better understand Actor in Swift. If you feel any doubt or queries please comment below.
Thanks for the read this blog and if you want to visit my other blogs click here.