قالب وردپرس درنا توس
Home / IOS Development / Swift Tip: Sharing code between Backend and Frontend

Swift Tip: Sharing code between Backend and Frontend



Over at Swift Talk, we have been concerned with building a new Swift Talk client app in SwiftUI. Because our backend is already written in Swift, we can now share a bunch of code between the client and the server.

As a first step, we took out our Tiny Networking library in their own Github project. It's a Swift package, and with Xcode 11 it's even easier to use across projects.

Then we went to the low hanging fruit: sharing display help functions. This gives us a consistent production between our backend and client applications. For example, we share custom formats to display an episode's duration and custom date formats.

Finally, one of the most interesting issues is the JSON models we use for the API. The background provides a JSON list of episodes and collections, and we generate it using the Codable infrastructure. To keep things flexible we have the following setup:

In our backend, our model structure is called an episode Episode . Instead of doing this directly to JSON, we created a structure EpisodeView . One EpisodeView is so called because we use it as a (JSON) view on the original data. In our backend we can then fill it from an episode:

  extension EpisodeView {
init (_e: episode) {
self = episode show (
id: e.id.rawValue,
number: e.number,
title: e.title,
synopsis: e.synopsis,
url: Route.episode (e.id, .view (playPosition: null)). url,
small_poster_url: ePosterURL (width: 590, height: 270),
// ...
)
}
}

By distinguishing between the two types, we can change the original Episode structure, while keeping the same API. Similarly, our Episode struct should not know about the URLs of the episode itself, they are added when we create the view.

In our shared code we also reveal a JSON encoder and decoder. Inserting them into the common library makes it much easier to keep them in sync. For example, we must ensure that we encode and decode our dates using the same strategy. On our server we use the shared encoder, and in our client we use the shared decoder.

In the future, it will be nice to also share a written specification of routes between the server and the client in a way similar to Haskell's server library.

To follow our experiments with SwiftUI, subscribe to Swift Talk.


Source link