Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Hands-On Swift 5 Microservices Development
Hands-On Swift 5 Microservices Development

Hands-On Swift 5 Microservices Development: Build microservices for mobile and web applications using Swift 5 and Vapor 4

Arrow left icon
Profile Icon Ralph Kuepper
Arrow right icon
Mex$676.99
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3 (6 Ratings)
Paperback Mar 2020 392 pages 1st Edition
eBook
Mex$378.99 Mex$541.99
Paperback
Mex$676.99
Subscription
Free Trial
Arrow left icon
Profile Icon Ralph Kuepper
Arrow right icon
Mex$676.99
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3 (6 Ratings)
Paperback Mar 2020 392 pages 1st Edition
eBook
Mex$378.99 Mex$541.99
Paperback
Mex$676.99
Subscription
Free Trial
eBook
Mex$378.99 Mex$541.99
Paperback
Mex$676.99
Subscription
Free Trial

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
Table of content icon View table of contents Preview book icon Preview Book

Hands-On Swift 5 Microservices Development

Understanding Server-Side Swift

Swift is a very young language as it was just released in 2014. It was designed to be a language with an easy syntax but that is as powerful as C. In this chapter, you are going to learn why Swift is an excellent choice when it comes to developing server applications. Swift arrives as a fresh alternative to all current and established solutions.

This chapter will introduce you to the server side of Swift; the basic understanding of Swift itself is something you should be familiar with already. At first, you are going to look at Swift as a generic language and why it fits well into the server world. Afterward, we look at the performance Swift delivers compared to other web technologies. A review of the current state of Swift for servers and an introduction to the new features of Swift 5 will sum this chapter up.

The following topics will be covered in this chapter:

  • A quick review of Swift
  • Swift performance
  • Swift on the server
  • The features of Swift 5

Once you have read this chapter, you will be well prepared to start using Swift for your application.

Technical Requirements

A quick review of Swift

To write server apps in Swift, we require an understanding of where Swift comes from and how it fits into the world of server languages. Swift was invented by Apple engineers as an alternative to C-derivatives, for example, C++, and, Objective-C, Objective-C++. After initially keeping Swift proprietary Apple then released Swift as open source for macOS and Linux. You might have wondered why Apple would bother to make Swift available on Linux, as Apple doesn't usually release any Linux products (not even iTunes).

Swift was designed to be a native language from the very beginning. It means an application gets compiled into binary code that runs directly on the processor, making it the fastest way for an application to run.

When Apple released Swift for Linux, there was little application. The UI was still functioning only on Apple devices, but a good bit of the essential frameworks, Foundation, in particular, was functional on Linux. These frameworks opened the door for some early web frameworks that took Swift and connected it to C libraries that would allow Swift code to run as a web server.

The Perfect framework was the first framework that did this. In September 2016, Tanner Nelson wrote the first version of the Vapor framework, which was loosely based on the Laravel framework (PHP). In May 2017, Vapor 2 was released, which was the first Swift framework that didn't rely on a C library to provide web server functionality. In the meanwhile, IBM started to work on Kitura, yet another framework allowing Swift to be used for web applications.

In early 2018, Apple released SwiftNIO, which is a network library for Swift. You can think of it as "Netty for Swift" if you are familiar with Netty (Java). To put it simply: SwiftNIO provides a very foundational framework to operate in a network and in files, such as opening connections, sending data, receiving data, sending streams, reading streams, and similar operations.

By releasing SwiftNIO, Apple now gave developers an essential set of features to work on server applications. SwiftNIO, like Swift, was also released for Linux.

While Swift has so far been released for macOS and Linux only, work-in-progress versions of Swift and SwiftNIO for Android, Windows, and other platforms exist. While Apple has not announced any plans for support, as an open source project, Swift and NIO can undoubtedly grow in maturity on other platforms. Swift on Linux runs on all available Linux flavors, though only Ubuntu is officially supported.

Let's take a brief look at the history of Swift in the context of other programming languages.

From Fortran to Swift

In this section, we want to take a look at the development of Swift, from Fortran, a very old programming language, up until Swift.

The following diagram and the timeline next to it highlights well how Swift combines the best of numerous worlds:

It stands out that Swift was influenced by Rust, Ruby, Python, Haskel, and C#, making it a very modern language that copied some of the most loved features of the other languages.

Now, we have learned about the history of Swift and where its place is in the world of programming languages. Let's look at Swift's performance compared to other popular web technologies next.

Swift performance

Swift is competing with a good number of frameworks and languages. Some might argue that performance is only one out of many factors that should be considered when choosing a technology. While that is undoubtedly true, think of this: you want to build a project in a way where technology will not hold you back much. Facebook, as well as Uber, has spent years rebuilding and reworking their infrastructure. No matter what technology you choose, you will most likely refactor your application as well. However, having selected a stack that allows you to do so gracefully is crucial.

You could be looking at some raw benchmarks in this section, but I think it makes more sense to analyze with a bit more depth what performance holistically looks like for a project. When comparing Swift to its competition, you want to stay as clean and objective as possible; the following comparisons attempt to assess the situations objectively and as close to the real world as possible.

Almost any website can run with any of the languages available. The question is often not "Is it possible?" but rather "Does it make sense for us?". In some cases, speed and performance are more important than convenience. In other cases, it's the exact opposite.

Let's briefly dig into the following types of languages:

  • Scripting languages: PHP, Python, Ruby, JavaScript, and so on
  • Virtual machine languages: Java, .NET, and Scala
  • Native languages: Go, C, Rust, and Swift

Afterward, you will see some metrics of Vapor, the most popular Swift framework.

Scripting languages

Script languages are not being compiled into a native binary but interpreted on-the-fly. So, every request to the server is treated individually and mostly isolated. The server then calls the language interpreter to work through the requested file (index.php, for example). Every time a script is called the server program needs to be started again. Naturally, this is not the fastest way to respond to a request.

A lot of mechanisms to speed up this process were invented over the years. All of them are essentially trying to do the following:

  • Cache interpreted code.
  • Cache various outputs and inputs as a whole.
  • Reduce the amount of overhead.

A lot of optimization for these languages is solely the idea of caching what they have compiled already and then returning it from caches when appropriate. There is principally nothing wrong with this approach, but it makes it difficult to compare performance. You want to assume the worst scenario, which is an empty cache when evaluating the pure speed of an application. Caching can be added later—even to an already speedy application.

The most popular scripting languages include Ruby, Python, PHP, JavaScript, and Typescript. All of them have various environments and interpreters, some of which are faster than others. They all share that they are naturally not compiled into binary code and will consequently always fall behind native languages. On the other hand, they enjoy a rich community and have gained many fans due to their simplicity.

Let's look at some real-life examples of websites dealing with scripting languages.

Facebook

Facebook started all in plain PHP and over a decade came up with its own PHP-flavored server called Hack. Hack started out as an initial attempt to compile PHP to a native binary file. It failed, however, due to the unforeseeable internal structure of a PHP program (dynamic variables, inconsistencies, and so on). Hack ended up being a PHP version that was modified to fit Facebook's internal needs. However, Hack is now running as a Virtual Machine (VM), not as a native application.

The reasons for Facebook were that it wanted to keep its dependencies and existing libraries operational while also increasing performance. While Facebook shows that scripting languages can certainly get very performant, it also shows how discontented Facebook became over time with PHP.

Twitter

Twitter started, like Facebook, as a monolithic application. It was written as a Ruby-on-Rails application. However, the increase in traffic caused Twitter to rewrite its backend entirely using the Java Virtual Machine (JVM), which means programming languages such as Java, Scala, and Clojure were used. Twitter also specifically attributes the microservice architecture as part of its path forward with regards to meeting traffic needs.

Read https://www.slideshare.net/caniszczyk/twitter-opensourcestacklinuxcon2013 for more detailed information on Twitter's stack.

Uber

Uber has transitioned critical services from Python to Go by now. In this case, it was partially for performance, but not in the same way Facebook was affected. Uber needed some of its services to be fast, concretely, live position updates. Uber chose Go because it was able to get better performance.

It is interesting to see how big players have started to transition some of their services from scripting languages to native ones.

Let's explore VM languages next.

VM languages

The most commonly used language in this category is Java. JVM has a long track record for being an enterprise-class web technology. On the other hand, .NET by Microsoft allows you to write in a variety of languages; often, C# stands out as the most common one for server applications.

Right between JVM and .NET is Scala—which is a new language that can compile into either .NET or JVM.

VM languages have the advantage that they are pre-compiled. They are not interpreted on-the-fly like scripting languages but pre-compiled into VM-specific byte code, which is then run on the VM. It comes with a good performance boost.

Apple, IBM, and LinkedIn are three examples that are using Java in a lot of their infrastructure.

Because VM code runs on the actual VM, and the engine is an extra layer on top of the operating system, VMs typically need a lot of RAM to operate smoothly. It is very common for the JVM to run on multiple GBs of RAM even for relatively simple applications.

Read https://people.cs.umass.edu/~emery/pubs/gcvsmalloc.pdf for more information on JVM RAM usage.

Native languages

Swift is a native language that compiles into native apps! So are C and C++. C (and C++) is inevitably the fastest language because it is so close to machine code (leaving Assembler aside). Many scripting languages directly plug into C for this reason. Node.js, PHP, and Python often directly utilize C functions, and those will always be very fast. Naturally, a pure C server will be the fastest server you could develop.

So, why not write our servers in C, you might ask? The reason you don't necessarily want to do that is that C is not convenient or safe in terms of memory leaks. It is complicated (some say impossible) to write good memory-safe programs in C. For web projects, this problem leads to the creation of Go (sometimes referred to as Golang), Rust, and Swift. All three were invented with the thought in mind to keep the performance of C/C++ but get better memory safety.

Go and Rust kept a mostly C-like functional style whereas Swift got inspirations from other object-oriented languages such as Java and scripting languages such as Ruby and Python. All three languages compile into native code, which means they run faster by default than the other two types of languages. No clear metric would show if any of the three is faster than the others. A good programmer could probably create equally performant programs in either language.

All three languages have been picked up by major players for critical performance tasks. For Swift, big players using it for web services include the following:

  • Apple
  • IBM
  • Mercedes
  • Audi

The main reason Swift is exciting to big corporations is that a native application leaves a much smaller RAM footprint. Imagine what difference it can make if you can achieve the same results but only need 25% of your hardware.

Comparing frameworks

As said before, it is not easy to compare languages, let alone frameworks, to each other. One framework might be extremely fast in doing one job whereas completely slow in another position. The following metrics have been recorded with Vapor 3 and a few other frameworks. Take them with a grain of salt, and as technologies continually develop, don't use them as hard numbers because any software update can change the balance:

It shows how all three Swift frameworks perform well compared to other well-known frameworks. You can see that the Swift frameworks outperform the other frameworks, except for Go, quite significantly. The scripting languages do not perform well as they are not natively compiled. The key to performance is that Swift compiles natively and can run directly on the processor.

We have looked at the frameworks and Swift's performance overall, so let's look at some specific Swift features now.

Swift's features

Here is a summary of all of the things that make Swift an attractive choice for server development:

  • A modern language built with the modern paradigm
  • A native language with native performance
  • Very low RAM usage
  • Linux-friendly
  • Universal usage can create apps for other OSes as well

There are certain situations and ways in which other languages are faster than Swift; however, overall, Swift offers the most significant performance benefits through its native design and low RAM footprint. Let's now explore what Swift looks like on a server.

Swift on the server

What does it look like to run a Swift application on a server? When Swift was released as open source, it was released for Linux right away as well. Specifically, Swift favors the Linux flavor, Ubuntu. Hosting a Swift application is very different from traditional web hosting. If you get a web hosting package from companies such as GoDaddy, you will not see them say "Runs Swift 5". Most mainstream web hosters only offer scripting languages. The reasoning is simple:

  • Most applications use scripting languages.
  • Scripting applications can share the same server.

Swift, on the other hand, as a native language, is the actual web server itself. What that means is that your Swift application is directly responding to incoming requests. Let's look at the following aspects of server-side Swift:

  • A self-contained server
  • Linux/Ubuntu
  • SwiftNIO
  • Docker

Let's dive into it.

Self-contained server

A self-contained server is a program that does not need another program to run. A PHP script, for example, will run through at least two other programs: PHP (the compiler) and Nginx, Apache, or another HTTP(S) server. A self-contained server such as a Swift application, however, is the only application that needs to run; it answers HTTP(S) requests directly.

Let's look at a small Swift web server:

import Vapor
let app = try Application()

app.get("hello") { req in
return "Hello, world."
}
try app.run()

Without going into much detail, the crucial part is the last line:

try app.run()

The application does not close; it keeps running. What the framework (Vapor) and the network library (SwiftNIO) are hiding here is that the application is actively listening to incoming connections over TCP on a given port (8080 by default). So, incoming requests are answered directly by the application and, by extension, the return statement.

If you have a background in dealing with scripting web applications, you may find a lot of perks in self-contained servers. In scripting languages, every request is usually isolated. Every request is treated individually, and you have no access to the other requests that are coming in. Technologies such as Memcached are designed to bridge this for you to share information between requests.

In Swift servers, however, the process, the running application, is the same for all requests. You can share memory, objects, and instances across requests. It not only allows you to centralize some of your logic (such as the database), it also saves you a lot of memory and CPU power.

Now that you have learned how a self-contained server operates, let's take a look at the hosting operating system: Linux/Ubuntu.

Linux/Ubuntu

When Swift was open-sourced, it was delivered Linux-compatible. Ubuntu is the official flavor of Linux that Swift currently supports. Numerous other platforms that are Linux-based are being developed currently; for servers, the best option was and remains Ubuntu.

Ubuntu has been and still is a favored Linux-distribution for server applications way before Swift. A lot of other technologies are running reliably and well on Ubuntu, and so it is not surprising Apple decided to support Ubuntu primarily. Since Ubuntu is also open source and has a large user base, it is unlikely that using Ubuntu for Swift applications will disappoint. Initially, Swift on Linux had some compatibility issues; however, with every Swift version, those have been eliminated.

In the distant future, it is thinkable that Swift applications might run on other platforms, including Windows and it might be another hosting option, but you might ask why you would want that since Linux has been reliable and stable. According to one of Swift's authors, Chris Lattner, "the ultimate goal for Swift has always been and still is total world domination. It's a modest goal."(https://oleb.net/blog/2017/06/chris-lattner-wwdc-swift-panel/#in-which-fields-would-you-like-to-see-swift-in-the-future)

So, for a Swift app to run on a Linux server requires a few libraries and tools to be installedmost of which can be done with package managers. As the Swift ABI is still maturing, you will almost always deliver the source code with your app. The server will then compile it into the executable you need for the respective OS version. As time goes on, this might soon change into a more library-oriented approach in which you can compile locally and simply move the compiled file.

You can already compiling the executable and move it by itself. The problem is that the target OS might not have the correct Swift libraries installed, or you might not have the right OS handy (for example, compile on macOS while wanting it to run on Linux).

To conclude, right now Ubuntu is the most promising and reliable way to launch a Swift application on a server. In this next section, we will explore how to achieve that without necessarily having Ubuntu running.

After looking at the actual OS that will run Swift, let's explore an alternative that allows Swift to run on other hosts as well: Docker.

Docker

When deploying your application, you can run it on macOS or Ubuntu. In the world of servers, it is a lot more economical to use Ubuntu than macOS (as macOS is only supposed to run on Apple hardware, whereas Ubuntu can run on any hardware). So, you want an Ubuntu server running for Swift. Let's talk about a popular and essential way to make things easier. Docker has been an upcoming trend over the last years. It is a container system that allows for operation-system-level virtualization. What that means is that you can run applications on your machine as if you have another operating system installed.

Docker containers are packages that include everything to run certain software. For example, the Swift container has everything you need to run Swift applications in Docker. Instead of using separate kernels during virtualization (like many VMs do), Docker uses the same kernel and isolates the resources and RAM for each container.

The implications of Docker are huge, especially for microservices: instead of having to deal with many different servers for an application, it is now possible to only deal with Docker containers. So, particularly when developing a microservices application, it is beneficial to run multiple services in separate Docker containers as they all run on the same hardware. It also allows for an interesting scaling opportunity since the applications operate without needing to worry about the underlying OS. For example, if you need to run 100 instances of one service, you could run it on one big server or 20 smaller servicesyour application won't know nor notice the difference.

The relevant elements of Docker are the following:

  • Images: These contain everything to run.
  • Containers: These have image instances that are running.
  • Repositories: Like GitHub, these are just for Docker images.

Furthermore, a Docker container can specify how much CPU and RAM it needs. This prevents applications from stealing resources from each other.

Let's now look at the last central piece of server-side Swift: SwiftNIO.

SwiftNIO

What is SwiftNIO? It is the official library Apple offers for managing and dealing with network connections and data streams, including filesystems. SwiftNIO provides all of the tools, protocols, and features you would need to operate in a network.

Before SwiftNIO, Swift server applications had to rely mostly on external C libraries. While this is not a problem in principle, having a pure Swift network library allows for better debugging and cleaner code.

SwiftNIO is a big step forward to the server-side Swift world since it standardizes network communication and delivers the toolsin Swiftyou need to build performant and reliable network applications. Apple has invested a lot of time and energy into SwiftNIO for it to be the main go-to tool when it comes to the network.

At this point, SwiftNIO is used in all major network libraries and frameworks that are developed for server applications in Swift. The convenient part of it is that framework developersand by extension, youdon't need to worry about debugging hardly any network issues anymore because Apple has taken that part over.

For all the intents and purposes of this book, SwiftNIO is something essential to be aware of, but it will mainly stay in the background. Vaporalong with other frameworksbuild around NIO in a developer-friendly way.

SwiftNIO allows us to operate asynchronously, we can send and receive data without having to worry about the exact timing or the network connection. This leads us to look at asynchronous events in general.

Asynchronous events

If you have dealt with network connections in the past, you will be familiar with the concept. There are two ways of looking at requests: synchronously and asynchronously.

Synchronously means you send a request (for example, to a server) and your code will wait for a response before it continues. An example would look like this. This is the actual code from a Vapor 2 project:

let user = User()    // User is a model that is connected to a database
user.id = 2 // set some attribute
try user.save() // saves this model to the database
print("saved") // this line is called after we saved

The last line is only called after the user is saved; the whole program waits for the saving process to be finished. In contrast to the synchronous approach is the asynchronous method. The following is the same code, now written for Vapor 4:

let user = User() 
user.id = 2
return try user.save(on: request.db) { _ in
print("saved")
}

You can see here that we are returning an EventLoopFuture<User> (line 3), but we are also not printing the "saved" string right after the return statement (because it would never be called), but we put it in a callback function. The fundamental difference here is that deal with the fact that we do not know when the user is saved. The database might be busy or slow; it might take 1 or 10 seconds. But when it is saved, we know that the callback function is called and then we print the "saved" string.

SwiftNIO is all based on the concept of asynchronous events; it handles all of the magic in the background for us, and we do not have to worry about it.

The reason we are not using synchronous calls (anymore) is that it can and most certainly will create problems for us down the line. Synchronous events in an asynchronous environment (which networks are) create issues that can look like deadlocks or threading complications. Using synchronous code causes threads to "wait" until they have finished; using asynchronous frameworks allows us to use the CPU resources in the meantime for different activities.

Now, let's look at some of the new features Swift 5 has brought to the table.

Features of Swift 5

You already have an understanding of how Swift works. In this section, we are looking at some of the newest features that Apple has released at the time of writing this book. There are a lot of bug fixes and changes in every Swift update, but the following features are particularly noteworthy for us in Swift version 5:

  • ABI stability
  • Raw strings and UTF8 strings
  • Result type
  • Future enum cases
  • Flattening nested optionals

There are a couple more interesting new features of Swift 5. However, this section only contains the ones that will be most relevant for server development. Take a look.

ABI stability

One particularly interesting new feature is that Swift is now ABI-compatible with version 5.0 and later ones. It means that libraries, frameworks, and applications could have different Swift versions but remain compatible with each other. As the number of libraries and frameworks for server-side Swift keeps growing, this will be a significant improvement to prevent version locks.

For example, you write your application with Vapor 4.0 and Swift 5, but then a little later Swift 6 is released. Let's pretend Swift 6 is somewhat incompatible with Swift 5. You can then rely on the fact that Vapor 4.0 can be compiled with Swift 5 and your app with Swift 6 while they can still run together without any conflicts.

It also opens the door to deliver applications, libraries, and executables without having to deliver the code. While this is possible already, every compiled Swift application is self-contained and specific to a platform at this point. As ABI stability will be increasingly adopted, it could be possible to not have to compile frameworks and libraries anymore, but just use the delivered libraries.

ABI stability is by far the most important improvement. Next to it are raw strings and UTF8 strings.

Raw strings and UTF8 strings

Swift 5 has rewritten how it deals with strings internally. Most of it is under the hood and not of practical relevance, but this one has some actual usage: raw strings.

They allow you to write a string that is not interpreted in any way, as in this example:

let rawString = #"This is a raw string with some "quotations marks" that are not being interpreted."#

Earlier versions of Swift would understand the quotation marks as the end of the string, but Swift 5 accepts them now. If you needed to use a variable within a raw string, you could still do that like this:

let age = 27
let rawString = #"My age is \#(age)." // string interpolation happens
// almost like before in raw strings

Raw strings will be useful whenever you have a lot of special characters within a stringlike in regular expressions, for example. On the subject of strings, Swift 5 switched from UTF16 to UFT8 strings, which caused a massive increase in performance.

Strings are important in almost every application, and seeing this improve is extremely helpful for us. Next, we want to look at the result type in Swift 5.

Result type

Swift 5 introduces a result type for common functions in which the result is either of the expected type or a failure. It is implemented as an enum with only two cases: success and failure.

Let's assume we build a user login and the result might either be the user itself or an error. For purposes of simplicity, let's consider the error in our case would be WrongPasswordError. In a real-world example, there would probably be more errors (timeout, connection, and so on):

func userLogin() -> Result<User, Error> {
if (...) {
return .success(user) // assume we got the `user` from somewhere
}
return .failure(WrongPasswordError)
}

When we are now trying to deal with a login attempt, we can nicely filter out the result:

switch userLogin() {
case .failure(let error):
// ...
break
case .success(let user):
// ...
break
}

The nice additional benefit to this type is that it can be used in asynchronous and complex code and allows for standard ways of dealing with errors. As frameworks and libraries adapt to this type, it will allow for predictable error handling.

Future enum cases

Imagine you have an enum :

enum ConnectionError: Error {
case timeout
case badRequest
}

If you are checking an error from a result, you will do it like this:

switch (error) {
case .timeout:
print("timeout")
case .badRequest:
print("bad request")
default:
print("another request")

As frameworks and libraries develop, the ConnectionError enum could be extended by a future version of a framework or library. Adding another case to the enum could look like this:

enum ConnectionError: Error {
case timeout
case badRequest
case denied
}

If a newer version of a framework updates this, it will cause your old code to select the default case, and you would not even notice that there is a new case. By adding a little attribute, @unkown, to the default case, you tell the compiler to warn you if the switch block is no longer exhaustive. This is a huge benefit to making sure enum cases are exhaustive even when new cases come along later on. Our switch statement now looks like this:

switch (error) {
case .timeout:
print("timeout")
case .badRequest:
print("bad request")
@unkown default:
print("an unkown request request")

The added case for the enum will now cause a compiler warningbut it won't break our code. This is important as this might happen in other external libraries as well. So, you don't need to worry about it in terms of compiling your software, but it is beneficial to be informed about this change. Swift 4.2 would not notify you nor would it break the code.

Flattening nested optionals

This addresses a problem where you are trying to get the return value of a function from an object that might be null. For example, we have a Product class that has a getPrice() function that returns an Int instance:

class Product {
func getPrice() throws -> Int {
return 10
}
}
var product:Product? = nil
var price = try? product?.getPrice()

In Swift 4.2, price would be an "optional optional Int" (Int??); however, in Swift 5, we can change the last line to this:

var price = try? product?.getPrice()

And now we only have one level of optionals as opposed to two. While this example is elementary, it is a powerful feature as you might be chaining a lot of optional functions together in a server application.

We have now seen what new features Swift 5 brings; a lot of them are very useful for backend development. In the next chapter, we will look at Vapor, the most popular server-side Swift framework.

Summary

In this chapter, you looked at the history of Swift and why it stands out from other languages. You then learned why Swift has been leaning toward server development from the beginning. After looking at Swift's performance compared to other languages and frameworks, you learned about Swift on the server and what is currently supported. Docker and SwiftNIO should be terms you can explain by now. Finally, you explored the features of Swift 5 and have seen examples of what the changes could look like in practice.

Go through the Questions section to validate your understanding of Swift on the server.

In the next chapter, you are going to explore the Vapor framework and you will be set up to create web applications with Vapor and Swift.

Questions

To see whether you understood the gist of server-side Swift, try answering the following questions:

  1. Why is Swift being a native language helpful?
  2. What is the preferred OS for server-side Swift applications at the moment?
  3. What is SwiftNIO?
  4. How does Docker help?
  5. Name three of the added benefits of Swift 5.
Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Understand server-side Swift development concepts for building your first microservice
  • Build microservices using Vapor 4 and deploy them to the cloud using Docker
  • Learn effective techniques for enhancing maintainability and stability of your Swift applications

Description

The capabilities of the Swift programming language are extended to server-side development using popular frameworks such as Vapor. This enables Swift programmers to implement the microservices approach to design scalable and easy-to-maintain architecture for iOS, macOS, iPadOS, and watchOS applications. This book is a complete guide to building microservices for iOS applications. You’ll start by examining Swift and Vapor as backend technologies and compare them to their alternatives. The book then covers the concept of microservices to help you get started with developing your first microservice. Throughout this book, you’ll work on a case study of writing an e-commerce backend as a microservice application. You’ll understand each microservice as it is broken down into details and written out as code throughout the book. You’ll also become familiar with various aspects of server-side development such as scalability, database options, and information flow for microservices that are unwrapped in the process. As you advance, you’ll get to grips with microservices testing and see how it is different from testing a monolith application. Along the way, you’ll explore tools such as Docker, Postman, and Amazon Web Services. By the end of the book, you’ll be able to build a ready-to-deploy application that can be used as a base for future applications.

Who is this book for?

The book is for iOS, iPadOS, and macOS developers and Swift programmers who want to understand how Swift can be used for building microservices. The book assumes familiarity with Swift programming and the fundamentals of the web, including how APIs work.

What you will learn

  • Grasp server-side Swift development concepts using practical examples
  • Understand the microservices approach and why Swift is a great choice for building microservices
  • Design and structure mobile and web applications using microservices architecture
  • Discover the available database options and understand which one to choose
  • Scale and monitor your microservices
  • Use Postman to automate testing for your microservices API
Estimated delivery fee Deliver to Mexico

Standard delivery 10 - 13 business days

Mex$149.95

Premium delivery 3 - 6 business days

Mex$299.95
(Includes tracking information)

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Mar 02, 2020
Length: 392 pages
Edition : 1st
Language : English
ISBN-13 : 9781789530889
Vendor :
Apple
Languages :
Concepts :
Tools :

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
Estimated delivery fee Deliver to Mexico

Standard delivery 10 - 13 business days

Mex$149.95

Premium delivery 3 - 6 business days

Mex$299.95
(Includes tracking information)

Product Details

Publication date : Mar 02, 2020
Length: 392 pages
Edition : 1st
Language : English
ISBN-13 : 9781789530889
Vendor :
Apple
Languages :
Concepts :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just Mex$85 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just Mex$85 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total Mex$ 2,153.97
Mastering Swift 5.3
Mex$799.99
Learn SwiftUI
Mex$676.99
Hands-On Swift 5 Microservices Development
Mex$676.99
Total Mex$ 2,153.97 Stars icon

Table of Contents

18 Chapters
Introduction to Microservices Chevron down icon Chevron up icon
Understanding Server-Side Swift Chevron down icon Chevron up icon
Getting Started with the Vapor Framework Chevron down icon Chevron up icon
Planning an Online Store Application Chevron down icon Chevron up icon
Creating Your First Microservice Chevron down icon Chevron up icon
Application Structure and Database Design Chevron down icon Chevron up icon
Writing the User Service Chevron down icon Chevron up icon
Testing Microservices Chevron down icon Chevron up icon
Product Management Service Chevron down icon Chevron up icon
Understanding Microservices Communication Chevron down icon Chevron up icon
Order Management Service Chevron down icon Chevron up icon
Best Practices Chevron down icon Chevron up icon
Hosting Microservices Chevron down icon Chevron up icon
Docker and the Cloud Chevron down icon Chevron up icon
Deploying Microservices in the Cloud Chevron down icon Chevron up icon
Scaling and Monitoring Microservices Chevron down icon Chevron up icon
Assessment Answers Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3
(6 Ratings)
5 star 33.3%
4 star 0%
3 star 16.7%
2 star 33.3%
1 star 16.7%
Filter icon Filter
Top Reviews

Filter reviews by




Carmi Weinzweig May 25, 2020
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Starting with a user service (including sending mail confirmations), the author develops a full micro services architecture built with the latest version of Vapor (Vapor 4). I started with only a little Swift experience and as I have progressed through the book, I have developed a good understanding of both Vapor 4 and why/how to use a microservice architecture. The author has been great about updating the code as Vapor 4 moved from Beta to release.The book develops the back end for an online store and covers everything from handing multi-service user authentication to deploying with Docker/Kubernetes on AWS, Google Cloud Platform (GCP) (although I have not really looked at that section), and Digital Ocean (a great less expensive option for certain kinds of deployments).I saw another review (part of what got me to write this one) and I am not sure what problems he had. It might be he was not working with the right version of Vapor (it was in its final release cycle and updating frequently). I purchased the book on the Apple Book Store (I had an iTunes gift card I wanted to use), and one of the great features of the digital versions is that they get updated as things change (very valuable for technical books).Finally, I recommend that anyone reading this book, join the Vapor community on Discord. The authors of most of the Vapor/Server-Side Swift books are there, and have happily helped as I have been developing my personal project (a web comic and media site), even with other authors’ books.The book starts with great explanation of why one would want to use microservices and what the downsides are as well. The author then explains how one can move from a monolithic app to a microservices architecture, by moving components one at a time, and even using it for add new functionality.Next the author discusses server-side Swift explaining some of its benefits and why Vapor was used as the book’s platform.The book then gives an introduction to Vapor covering its architecture and ORM (Fluent). While it is not a full Vapor 4 tutorial, it is more than enough to get started.With that background, the author begins to layout the architecture of the application being built. Starting with a user service that includes basic address management, the author explains how to test and debug microservices.The product management service is next, and now with two services, the book details how to communicate among one’s microservices. It talks about best practices and pitfalls to avoid. After adding the order service, it is time to cover deployment.Starting with options for hosting and a discussion of the current state of Swift on Linux, the book works its way through what is needed to deploy and scale a Swift-based server-side application. Again, as with its material on Vapor, this is not a complete Docker, Kubernetes, AWS, GCP or Digital Ocean tutorial, but more than enough to get started and understand what else one needs to learn.In addition to the book itself, the author has made available all the source code for the projects being built making it a great starting point for someone working on a real system. Overall, I think it is a great starting point for someone interested in exploring both server-side Swift and microservices.
Amazon Verified review Amazon
Pete D Jun 15, 2020
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Being a novice at writing swift Vapor backends, I have a bit of familiarity with how they work. In addition, I’ve been exposed to microservices quite a bit but have never written them myself. Given my knowledge, I found this book to be the perfect intersection of the two. The author does an impeccable job teaching users the concepts of microservices via a swift vapor implementation. In addition, the author does well to describe asynchronous concepts, jobs processing, and other backend type work that goes beyond your typical REST API framework. You’d be hard pressed to find a better swift / vapor microservices backend book.Granted, there are some minor mistakes in this book, however they are simple and reading over it it’s easy to fix when you follow along with the code. In addition, the content is subject to change as it was written while Vapor 4 is in beta. The author says he will update this book when Vapor 4 makes a full public release.How do I know this? Well the author is very involved in the Vapor community, and actively contributes to the chat, and answers anyone’s questions that they have on the book. I personally had some issues when implementing some code, and while it was not due to his fault, but rather a beta issue with Vapor 4, he promptly assisted me in resolving the issue.I’d not like to emphasis small mishaps with this book, because they don’t have much relevance in my opinion. When you purchase this book, you’re not only getting quality content, but you’re getting personal help from the author, and future updates. Now for the price of this book, it’s well worth more than the cost. Along with being in the community, you’ll feel right at home, and the author is sure to make you feel that way too.I’d highly recommend this book, not just for the Vapor 4 side of things, but showing you how to create microservices that are interactive. That in itself is timeless information that will be useful for plenty of years to come.
Amazon Verified review Amazon
Vital Zanko Dec 26, 2023
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3
This is a quite good book uncovering Vapor subject especially to someones who are unfamiliar with Swift back end frameworks. Yet that only means its text is mostly useful to get in.But code examples are not well-organized: the author asks to "copy-paste" code from repos of previous chapters when a happy reader is interested in out-of-box repository for the chapter (a reader can be not interested much in the previous chapters and either he should not find out proper steps in them; it makes more sense to provide out-of-box repository that a reader can start easily and may alter working code on his own whether he wishes).
Amazon Verified review Amazon
E. Leonard Jun 19, 2021
Full star icon Full star icon Empty star icon Empty star icon Empty star icon 2
I returned the book for the following reasons:The source code in the book bears little resemblance to the related Git repository.Even the supplied source code could not be run despite the .env environment being set as required. I could have muddled through and patched it together with a lot of research and trial and error but that defeats the point of a 'how to' book and means you're flying solo, in which case you might not have bothered with the book. I would like o see the book brought up to date and better (no assumptions made) directions in the text. The step1, step 2, step 3 type instructions in the book make a lot of assumed knowledge leaps early on and it requires reading a few times to clear the mist.I so wanted it to be great and give it a 5-stars as there's not enough server-side Swift in the world, unfortunately, this needs a bit of work to get it to a higher rating.
Amazon Verified review Amazon
Wunschzettel Kinder Oct 29, 2022
Full star icon Full star icon Empty star icon Empty star icon Empty star icon 2
This book would need quite a bit of editing in many directions, some examples:- Explanations/didactics often could be better "The difference to EventLoopFuture is that a Future is what is the result of a Promise" (Page 60)- Missing checks on examples, Chapter 2 compares source for Swift 4.2 and Swift 5 and points out the difference. There is no difference in the book, the lines are identical. (Page 49)- Dependencies between chapters "The following components need to be installed: [...] Docker [...]" (Chapter 5), "Installing Git and Docker" (Chapter 6)- Teaches bad behavior: creating Public / Private Keys via web service - it does mention you should create public/private keys using command line tools, but neither why not how to (book refers to the website) (Page 125/126)In my opinion the book gets a bit better at around chapter 6 / 7, but still could be vastly improved.As of today, I would suggest to buy "Server-Side Swift with Vapor" instead.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela