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

You're reading from   Hands-On Swift 5 Microservices Development Build microservices for mobile and web applications using Swift 5 and Vapor 4

Arrow left icon
Product type Paperback
Published in Mar 2020
Publisher Packt
ISBN-13 9781789530889
Length 392 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
Ralph Kuepper Ralph Kuepper
Author Profile Icon Ralph Kuepper
Ralph Kuepper
Arrow right icon
View More author details
Toc

Table of Contents (19) Chapters Close

Preface 1. Introduction to Microservices 2. Understanding Server-Side Swift FREE CHAPTER 3. Getting Started with the Vapor Framework 4. Planning an Online Store Application 5. Creating Your First Microservice 6. Application Structure and Database Design 7. Writing the User Service 8. Testing Microservices 9. Product Management Service 10. Understanding Microservices Communication 11. Order Management Service 12. Best Practices 13. Hosting Microservices 14. Docker and the Cloud 15. Deploying Microservices in the Cloud 16. Scaling and Monitoring Microservices 17. Assessment Answers 18. Other Books You May Enjoy

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 string—like 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 warning—but 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.

You have been reading a chapter from
Hands-On Swift 5 Microservices Development
Published in: Mar 2020
Publisher: Packt
ISBN-13: 9781789530889
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at R$50/month. Cancel anytime