Improve your networking with macro powered service layer for Swift
Over the years most of us used some 3rd party frameworks to write better service layers such as Alamofire, AFNetworking and others. The introduction of Async/Await (also known as Swift Concurrency) and then Swift Macros makes those frameworks obsolete and outdated. Why? Because now you can build service layers much, much easier thanks to frameworks such as Snowdrop.
Snowdrop is a type-safe, protocol based, macro powered framework that allows you to build network services with ease. To create one, you just need to declare a protocol like this:
Upon expanding macro, you’ll get a class similar to this:
Pretty cool, huh? Snowdrop automatically creates implementation of your request methods and alternative declarations with _queryItems parameter if you’d want to add some. Note that the second request has body parameter. Snowdrop automatically recognizes it as something you’d like to send as HTTP request’s body. If you want to name this argument differently, you may use Body macro.
Now, let’s say you’d like to put some variables in your path. Snowdrop automatically associates variables you put in your path with arguments in your request’s declaration. Let’s look at an example.
As you can see, you can inform Snowdrop you have a variable in your path by wrapping it with { }. But what if you want to put default value to your variable? As you know, you cannot declare default values in protocols but Snowdrop has a simple and intuitive solution for that. Just put it in your path like this:
In this case Service implementation will look like:
Let’s say, we want to also prepare a mock version of the service above. Once again this is something Snowdrop can do for you. Just use Mockable macro to your service and Snowdrop will create BackendAPIServiceMock for you with implementation like this:
Once we’re ready to go, time to execute our first request.
Quite easy, right? If you’d like to learn more about Snowdrop and try it yourself, check Snowdrop repo on GitHub.