Use Swift Actor to handle APIs calls

Gianluca Annina
2 min readApr 1, 2022

--

In this tutorial we will explain what an actor is and how to use it to handle APIs calls.

But why should you use an Actor? Normally it’s not recommended to use an Actor because it will lead to a concurrent call of the different APIs and slow down all the operations. The optimal situation to use an actor is when you need to call more API functions exactly one after another.

(In collaboration with Giuseppe Carannante and Domenico Marino)

1. Swift Actor

In swift we define an actor as a particular class that doesn’t support inheritance (means there’s no need for features like the convenience and required initializers, overriding, class members, or open and final statements).

An actor is really useful to prevent data races because it creates synchronized access to its data.

In order to create an actor in swift we need to use the keyword actor:

2. Create a new Model

  • Now let’s add a JSON decoder function that will be needed to convert APIs calls results from JSON to our custom Model:

3. Handle DataBase Errors

  • In order to help us handling database errors we define a little enumeration as shown below:

4. Actor Class

  • Let’s go back to our actor and define the URLComponents to access to your APIs as shown below:
  • Now we need the code below to allow our database to accept and decrypt the JSON files that we sent to the database:

Be careful when setting the values for “method”, you should write in all caps the type of operation you want to use (Example: “PUT”, “POST”…).

  • The final class contains an example of all the CRUD operations:

5. Visualize your actor

To implement your actor inside your view you can choose between two different options:

1.

The code will be executed only after tapping on the text.

2.

The code will be executed as soon as the view is presented.

If you want to download the full project click here: GitHub

Want to Connect?In case you have any problem you can contact us on discord:Giuseppe Carannante — Giuseppe Carannante#3488Domenico Marino — Domenico Marino#1203Gianluca Annina — SidusProxy#1914

--

--