Group Group Group Group Group Group Group Group Group

Creating an API Helper Library for SwiftNIO | raywenderlich.com

In this SwiftNIO tutorial you’ll learn how to utilize the helper types from SwiftNIO to create an API library that accesses the Star Wars API.


This is a companion discussion topic for the original entry at https://www.raywenderlich.com/4623672-creating-an-api-helper-library-for-swiftnio

In the code snippet right above the ‘Extending the Models’ section, it’s missing the generic R.

Why doesn’t the code make use of keyDecodingStrategy to handle snake case, instead of doing the tiresome skinColor = "skin_color"?

Also, what’s with the use of _ as an instance var prefix? Why was it used? e.g. _homeworld.

Hey @isuru, thanks for mentioning this. I’ve updated the snippet in the article.

@rae, the reason there is no use of keyDecodingStrategy is because of the _homeworld like properties. Since they’re not following any of the keyDecodingStrategy conventions (neither camel nor snake case) we have to write custom CodingKeys for them, and thus also for our other properties.

As for why we use these underscored properties in the first place: The _homeworld like properties are used to hold the data we get from the API. In this case a URL pointing to an other resource. Next to those, we have a non underscored property that’s a computed property, like this:

public var homeworld: EventLoopFuture<Planet> {
  return client.get(URL(string: _homeworld))
}

This means that instead of exposing a URL to our users in the homeworld property, we expose an EventLoopFuture<Planet>, which is more useful and clean, saving the end user from having to then go and fetch the actual Planet object. The _ itself does nothing here, it’s purely a convention picked up from Python where private properties are prefixed with _. I hope this answers your question, if not, feel free to let me know, happy to further explain :]

actually there’s typo in second update on get function on tutorial

func get<R>(_ route: URL?) -> EventLoopFuture where R: Decodable & SwapiModel

EventLoopFuture should abstract R

func get<R>(_ route: URL?) -> EventLoopFuture<R> where R: Decodable & SwapiModel