Thursday, November 26, 2020

Mastering Swift 5.3

The latest edition in my Mastering Swift series has just been released.  It has been updated for the latest release of Swift and has two new chapters.

Over the years, Mastering Swift has proved itself among developers as a popular choice as an in-depth and practical guide to the Swift programming language. This sixth edition comes with the latest features, overall revision to align with Swift 5.3, and two new chapters on building swift from source and advance operators. 

From the basics of the language to popular features such as concurrency, generics, and memory management, this in-depth guide will help you develop your expertise and mastery in the language.

As you progress, you will gain practical insights into some of the most sophisticated elements in Swift development, including protocol extensions, error handling, and closures. The book will also show you how to use and apply them in your own projects. In later chapters, you will understand how to use the power of protocol-oriented programming to write flexible and easier-to-manage code. Finally, you will learn how to add the copy-on-write feature to your custom value types, along with understanding how to avoid memory management issues caused by strong reference cycles.

By the end of this book, you will have mastered the Swift 5.3 language and developed the skills you need to effectively use its features to build robust applications.

Chapter 1Taking the first steps with Swift, will introduce you to the Swift programming language and discuss what inspired Apple to create Swift. We'll also go over the basic syntax of Swift and how to use Playgrounds to experiment and test Swift code.

Chapter 2, Swift documentation and installation, will introduce the user to the swift.org and swiftdoc.org sites and how the swift development process works.  We will go through the complete process of building swift from source and installing it on both the Linux and Mac platforms.

Chapter 3Learning about variables, constants, strings and operators, will introduce variables and constants in Swift and when to use them. There will be brief overviews of the most common variable types with examples on how to use them. We'll conclude this chapter by showing examples of how to use the most common operators in the Swift language

Chapter 4Optional Types, will explain what optional types really are, what are the various ways to unwrap them. For a developer who is just learning Swift, optional types can be one of the more confusing items to learn.

Chapter 5Using Swift collections, will explain Swift's array, set, and dictionary collection types and show examples on how to use them.

Chapter 6Control Flow, will show you how to use Swift's control flow statements. These include looping, conditional, and control transfer statements.

Chapter 7Functions, This chapter is all about functions in Swift.  We will show how to define and properly use them

Chapter 8Classes, Structures and Protocols, This chapter is dedicated to Swift's classes, structures and protocols. We'll look at what makes them similar and what makes them different.

Chapter 9Protocol and Protocol Extensions, will cover both protocols and protocol extensions in detail since protocols are very important to the Swift language, and having a solid understanding of them will help us write flexible and reusable code

Chapter 10Protocol Oriented Design, will cover the best practices of Protocol Oriented Design with Swift.  

Chapter 11Generics,  will explain how Swift implements generics. Generics allow us to write very flexible and reusable code that avoids duplication 

Chapter 12Availability and Error Handlingwill cover error handling in depth as well as the availability feature.

Chapter 13Custom Subscripting, will discuss how we can use custom subscripts in our classes, structures, and enumerations. 

Chapter 14Working with Closureswill show how to define and use closures in our code. This chapter concludes with a section on how to avoid strong reference cycles with closures

Chapter 15Advanced and Custom Operators, will show how to use bitwise and overflow operators.  We will also look at how we can create custom operators

Chapter 16Concurrency and Parallelism, will show how to use both Grand Central Dispatch and Operation Queues to add concurrency and parallelism to our applications

Chapter 17Custom Value Typeswill cover some advance techniques that the reader can use in their applications like copy-on-write and implementing the equatible protocol.

Chapter 18Memory Managementwill cover items like how Automatic Reference Counting (ARC) works, how much faster value types are as compared to reference types, strong retain cycles, weak vs strong references

Chapter 19Swift Formatting, will define a style guide for the Swift language that can be used as a template for enterprise developers who need to create a style guide

Chapter 20Adopting Design Patterns with Swift, will show you how to implement some of the more common design patterns in Swift. A design pattern identifies a common software development problem and provides a strategy for dealing with it

You can purchase a copy of my book from Amazon or from Packt Publishing.

Thursday, April 30, 2020

Compile Swift for Linux with its Toolchain and Package Manager

If you are unable to install Swift with pre-built binaries, you can compile it instead.  Compiling is a lot more complex and confusing than simply installing prebuilt binaries and I found that a lot of instructions do not build the Swift package manager which I consider to be a necessity when build anything more complex than a simple hello world application.  In this post we look at how we can build Swift with its full toolchain and package manager.

Install Dependencies

The first thing we need to do is to make sure we have all of the dependencies required installed.  The following command includes all dependencies I have needed to install on different flavors of Linux.  You will find that your distribution probably already has a lot of these preinstalled but to make sure you have everything, run this command.

sudo apt-get install git cmake ninja-build clang python uuid-dev libicu-dev icu-devtools libedit-dev libxml2-dev libsqlite3-dev swig libpython-dev libncurses5-dev pkg-config libcurl4-openssl-dev systemtap-sdt-dev tzdata rsync python-pip

If you want to build the documentation, you will need to install Sphinx as well.  This can be done with the following command:

 pip install Sphinx

Now that we have all of the dependencies installed, we need to get the swift source code.

Swift Source

To download the Swift source code, we will want to create a directory to download it too, change to that directory and then run the git command to get the source.  The following commands will download the swift source to a directory name swift-source.

mkdir swift-source
cd swift-source
./swift/utils/update-checkout --clone

Now that we have the source and cloned everything we need, lets build swift.

Build Swift 

Before you begin building Swift, know that it is going to take hours to build.  The exact time will depend on the type of system you are building it on.  The following command will build Swift, its toolchain and the package manager:

./swift/utils/build-script --preset=buildbot_swiftpm_linux_platform,tools=RA,stdlib=RA

Once this has built everything, which could take several hours, we will want to install it similar to what we did with the pre-built binaries in this post:  

Installing Swift

Now that we have built Swift from source, we are ready to install it and put it in our path so we can execute them easily.  I like to install the under the /opt directory, others prefer installing it under the /usr/local/sharedirectory.  What directory you put it under is totally up to you.  I will walk you through installing it under the /optdirectory, if you would like to put it someplace else simply replace the “/opt” in the paths with your install directory.  

Now let’s change to the /opt directory and create a directory named swift.  Once the swift directory is created, we will also need to change the permissions for the directory so we can read, write and execute files.  The following commands will do this:

cd /opt
sudo mkdir swift
sudo chmod 777 swift

The command chmod 777 swift will add read, write and execute permissions for all users of this computer.  I like to use this mode because then any user on the system can use it, however this can be considered a security issue because it also means anyone can modify the files.  Use this at your own risk and for production systems I would really look at who needs permissions for this directly and lock it down more.

Now we will need to move the Swift binaries that we downloaded to the swift directory.  To do this we will change to the swift directory, create a new directory for our build, change to the directory and copy the files over.  For this article I am building the 5.3-dev version of swift therefore I am using that for my directory name.  The following commands will do this:

cd swift
mkdir swift-5.3-dev
cd swift-5.3-dev
cp -R ~/swift-source/build/buildbot_incremental/toolchain-linux-x86_64/* ./

Now we will want to make a symlink to this directory called swift-current.  The reason for this is we will want to add an entry to our PATH environmental variable so the operating system can find the Swift executables without us needing to enter the full path.  If we set up this entry using the swift-current path rather than the swift.5.3-dev path.  This will allow us, when we install new versions of Swift, to simply change where the swift-current symlink points to and have everything work.   We will do this with the following command:

sudo ln -s /opt/swift/ swift-5.3-dev swift-current

Now we will need to create the entry in our PATH variable.  To do this you will want add the add /opt/swift/swift-current/usr/bin/ directory to the PATH variable in our .profile file located in your home directory.  Then update the environment The following commands will do this:

cd ~
echo 'export PATH=$PATH:/opt/swift/swift-current/usr/bin'  >> .profile
source ~/.profile

The last thing we need to do is to verify swift has been successfully installed. To do this, we can run the following command:

swift –version

The output should look something like this but with the version of swift that you installed

Swift version 5.2.2 (swift-5.2.2-RELEASE)
Target: x86_64-unknown-linux-gnu

Congratulations, you have now successfully installed Swift.


Installing Swift for Linux with Pre-built Binaries

The easiest and quickest way to install Swift for Linux is by installing pre-built binaries.  If you are using a LTS branch for Ubuntu, you can find links to download these binaries by going to the following page: https://swift.org/download/.  In this post we will look at how we can install Swift using these binaries however before we do that lets look at the possibility of installing Swift with pre-built packages on non-Ubuntu systems.

Install using a Linux package manger

If you are not using Ubuntu, you may still be able to install pre-built binaries through the package manager that comes with your system.  As an example, with CentOS you can very easily install swift with the following command:

sudo yum install swift-lang swift-lang-runtime.


Installing with the binaries from these package managers will be the easiest way to install Swift however what version is installed and if they stay up to date is dependent on the person that build these binaries.  To find out if your flavor of Linux has a Swift package, you will first have to determine which package manager is used by your system.  You will probably have either apt or yum as your package manager.  The easy way to determine which package manager you have installed is to run both the apt and the yum command.  After you run the command, you will see either the help message for the command if it is installed or a command not found error if the command is not installed.

Once you determine which package manager is installed, you can run one of the following commands to see if there are Swift packages for you flavor of Linux:

apt search swift-lang
yum search swift-lang

If no results are found, you could try searching for swift rather than swift-lang however you will find numerous results that are not the Swift language.  If you do have results from your search, you can install the package by using one of the following commands (Note: replace {package name} with the name of the package returned from the search):

sudo apt install {package name}
sudo yum install {package name}

To verify that Swift is properly installed once the packages are installed, look at the verifying installations section at the end of this chapter.

If swift is properly installed, then you should see the version number of the installed version of Swift.  I wish I could make these instructions were more specific however there is no way we could cover all flavors of Linux here and even if we were able to, there would be no guarantee that packages would not change tomorrow.  

Now let’s look at how we can download and install the Ubuntu binaries from the swift.org site.  

Installing using the swift.org binaries


If you ae using an LTS version of Ubuntu, the easiest way to install Swift is to install the pre-built binary, for your version of Ubuntu, from the swift.org site.  These are official release binaries built by the Swift community itself.  They release pre-binaries for Ubuntu with all official releases of Swift and also for the latest development branch if you want to try the latest and greatest. 

To install Swift with these binaries, the first thing we need to do is to download them from the swift.org site.  In your favorite browser go to the following URL,  https://swift.org/download/ and you should see a screen similar to this:


As you can see from this screenshot, that the latest official released version of Swift, at the time this book was written, is 5.2.2.  To download the pre-built binaries for Swift, you simply need to click on the version of Ubuntu that you are using and it will start the download. In this case I would download a file named swift-5.2.2-RELEASE-ubuntu18.04.tar.gz.  

The name starts off with the word swift because it contains the pre-built binaries for the Swift language, followed by the version number.  Next we see the word RELEASE because this is an official release version of Swift.  If it wasn’t an official release version, we would see the word DEVELOPMENT instead.  The end of the name tells us what platform the pre-built binaries are built for.  In this case they are built for Ubuntu 18.04.

Now we will need to unzip and untar the file.  To do this we need to run the following command:

tar -xzf swift-5.2.2-RELEASE-ubuntu18.04.tar.gz

You will want to substitute the file name in the previous command with the name of the file that you downloaded.  Once this command has finished, you should have a directory with the same name as the original file except it will not have the .tar.gz suffix. 

Before we install these binaries and set up our path, we will want to install the dependencies.  The following command will install the required dependencies:

sudo apt-get install clang libicu-dev

The required dependencies may change with future releases of Swift.  The same page that you downloaded Swift from also contains the list of dependencies.  You can verify that no additional dependencies are needed by referring to that page.

Now that the dependencies are installed, we are ready to install the Swift binaries and put them in our path so we can execute them easily.  I like to install the under the /opt directory, others prefer installing it under the /usr/local/share directory.  What directory you put it under is totally up to you.  I will walk you through installing it under the /opt directory, if you would like to put it someplace else simply replace the “/opt” in the paths with your install directory.  

Now let’s change to the /opt directory and create a directory named swift.  Once the swift directory is created, we will also need to change the permissions for the directory so we can read, write and execute files.  The following commands will do this:

cd /opt
sudo mkdir swift
sudo chmod 777 swift

The command chmod 777 swift will add read, write and execute permissions for all users of this computer.  I like to use this mode because then any user on the system can use it, however this can be considered a security issue because it also means anyone can modify the files.  Use this at your own risk and for production systems I would really look at who needs permissions for this directly and lock it down more.

Now we will need to move the Swift binaries that we downloaded to the swift directory.  To do this we will change to the swift directory and then move the untarred binaries, that should be located in the Downloadsdirectory, to the swift directory.  The following commands will do this:

cd swift
mv ~/Downloads/swift-5.2.2-RELEASE-ubuntu18.04 ./

Now we will want to make a symlink to this directory called swift-current.  The reason for this is we will want to add an entry to our PATH environmental variable so the operating system can find the Swift executables without us needing to enter the full path.  If we set up this entry using the swift-current path rather than the swift.5.2.2-RELEASE-ubuntu18.04 path.  This will allow us, when we install new versions of Swift, to simply change where the swift-current symlink points to and have everything work.   We will do this with the following command:

sudo ln -s /opt/swift/ swift-5.2.2-RELEASE-ubuntu18.04  swift-current

Now we will need to create the entry in our PATH variable.  To do this you will want add the add /opt/swift/swift-current/usr/bin/ directory to the PATH variable in our .profile file located in your home directory.  Then update the environment variables  The following commands will do this:

cd ~
echo 'export PATH=$PATH:/opt/swift/swift-current/usr/bin'  >> .profile
source ~/.profile

The last thing we need to do is to verify swift has been successfully installed. To do this, we can run the following command:

swift –version

The output should look something like this but with the version of swift that you installed

 Apple Swift version 5.3-dev (LLVM a60975d8a4, Swift afe134eb2e)
Target: x86_64-unknown-linux-gnu

Congratulations, you have now successfully built and installed Swift.  Now to verify that the package manager was successfully built and installed, run the following commands:

mkdir test
cd test
swift package init

If everything was successfully built you should see out similar to this:

Creating library package: test
Creating Package.swift
Creating README.md
Creating .gitignore
Creating Sources/
Creating Sources/test/test.swift
Creating Tests/
Creating Tests/LinuxMain.swift
Creating Tests/testTests/
Creating Tests/testTests/testTests.swift
Creating Tests/testTests/XCTestManifests.swift

You are now ready to go.

Tuesday, October 24, 2017

Why you should learn Generics


Over the past couple of years, I have been surprised with the number of senior level developers that I have meet that do not use Generics.  Not only do they not use generics but they actually have very little understanding of them.  In this article, I would like to explain why all developers should not only learn generics but use them regularly.  While this article focuses on the Swift programming language, the concepts of why you should learn and use generics will apply to almost any language that have generics similar to Swift.

I will start off by demonstrating the problem that generics solve.  Let’s say we are developing a new application and within this application we have the need to swap the value of two integer variables.  To meet this need, in Swift, we could very easily write a function like this:

func swapInt(_ a: inout Int, _ b: inout Int) {
    let tmp = a
    a = b
    b = tmp
}

This function could then be used like this:

var one = 1
var two = 2
swapInt(&one, &two)

Now, a few days or weeks later, as we continue to write the application, we discover a need to swap the values of two string variables.  We could then add another function to do this.  The following code shows this new function:

func swapInt(_ a: inout String, _ b: inout String) {
    let tmp = a
    a = b
    b = tmp
}

As time goes by we may end up with several functions like the previous swap functions but with different parameter types.  Instead of having all of these different functions, in the beginning we could have created one generic swap function that looked like this:'

func swapGeneric<T>(_ a: inout T, _ b: inout T) {
    let tmp = a
    a = b
    b = tmp
}

Notice that the generic version of the swap function uses a placeholder, capital T, rather than the actual parameter type.  This placeholder tells the compiler that we will define the type to use at runtime.  Since the T placeholder is used for both parameters, they are required to be of the same type.

We would use this generic function exactly like we would use the non-generic swap functions.  The following code illustrates this:

var one = 1
var two = 2
swapGeneric(&one, &two)

Now the parameters can be instances of any type as long as they are instances of the same type.  We could swap the values of two string types like this:

var one = “one”
var two = “two”
swapGeneric(&one, &two)

Swapping values isn’t too exciting so let’s look at something that does a bit more by seeing how we could use generics to create a very basic queue type.  The following code shows how to do this.

struct Queue<T> {
    private var items = [T]()
    
    public mutating func push(_ item: T) {
        items.append(item)
    }
    public mutating func pop() -> T? {
        if (items.count > 0) {
            return items.remove(at: 0)
        } else {
            return nil
        }
    }
}

We would use this queue type like this:

var queue = Queue<Int>()
queue.push(1)
queue.push(2)
print(queue.pop())
print(queue.pop())

One of the best things about this queue type is it is ready to accept any type.  We could very easily create an instance of the Queue type that would store String values like this:

var queue = Queue<String>()

One of the questions that someone new to generics may ask is: Why don’t we just use the Any type rather than generics?  In Swift, the Any type allows us to use instances of any type.  The following code shows how we could create a Queue type that used the Any type:

struct QueueAny {
    private var items = [Any]()
    
    public mutating func push(_ item: Any) {
        items.append(item)
    }
    public mutating func pop() -> Any? {
        if (items.count > 0) {
            return items.remove(at: 0)
        } else {
            return nil
        }
    }
}

The QueueAny type lets us create a queue that can contain any type similar to the previous generic queue however there are several disadvantages to this method.  The one disadvantage that we will focus on here is the ability to add any type to the queue.  For example this code would be perfect ok with the QueueAny queue:

var queueAny = QueueAny()
queueAny.push(2)
queueAny.push("Hi")

Notice how we are able to add both an integer and a string to the same queue.  The QueueAny type functions similar to how Arrays worked in Objective-C.  Now if we popped an item off the queue we would need to typecast it before we used any of the methods or properties of the type.  This does not allow us to have any compile time checks to make sure we are using the correct types in our queue and is prone to error, as any Objective-C developer can tell you.

With the generic Queue type, since we explicitly define the type of items stored in the queue, we are able to use the properties and methods of that type without the need to typecast.  This gives us the compile time checks that ensures we are using the correct types.

The answer to the question about why you should learn generics is:  Generics enable us to write very flexible and reusable code that is also very safe.  In this article we only scratched the surface of generics.  If you are unfamiliar with generics I would recommend taking the time to learn more about them.

In my Mastering Swift 4 book there is a chapter dedicated to generics that gives the reader a good introduction to generics which shows how to create generic functions, types and protocols.  We also look at using type constraints with generics and the new generic subscripting feature that was introduced in Swift 4.

In my Swift 4 Protocol Oriented Programmingbook we also have a chapter dedicated to generics.  In that chapter, we briefly cover generic types, protocols, type constraints and generic subscripting.  We also include more advance topics like how generics are used in the Swift standard library and how to use generics to implement the Copy-on-Write feature for custom value types.
  

Thursday, October 5, 2017

Announcing Two New Swift Programming Books


Swift is the definitive language of Apple development today. It’s a vital part of any iOS and OS X developer’s skillset, helping them to build the most impressive and popular apps on the App Store—the sort of apps that are essential to iPhone and iPad users every day. With version 4.0, the Swift team has added new features to improve the development experience—making it easier to get the results you want and customers expect.

The first book that was released in the Mastering Swift 4 book.  Inside this book, you’ll find the key features of Swift 4.0 and quickly learn how to use the newest updates to your development advantage. From Objective-C interoperability to ARC, to closures and concurrency, this advanced Swift guide will develop your expertise and make you more fluent in this vital programming language.

Mastering Swift 4 will give you in-depth knowledge of some of the most sophisticated elements of Swift development including protocol extensions, error-handling, design patterns, and concurrency, and guide you on how to use and apply them in your own projects. You'll see how to leverage the power of Protocol-Oriented program to write cleaner and easier to manage code. We will also show you how Apple uses Protocol-Oriented programming techniques in the Swift standard library.

Some key areas that are covered are:
  *  Dive into the core components of Swift 4.0, including operators, collections, control flow, and functions
  *  Create and use classes, structures, and enums
  *  Understand protocol-oriented design and see how it can help you write better code
  *  Develop a practical understanding of subscripts, optionals, and closures
  *  Add concurrency to your applications using Grand Central Dispatch and Operation Queues
  *  Implement Generics and Closures to write very flexible and reusable codes 
  *  Make use of error handling and the availability feature to write safer code

This book is for developers who want to dive into the newest version of Swift. If you are a developer that learns best by looking at, and working with code, then this book is for you. A basic understanding of Apple's tools is beneficial but not mandatory.

The second book that is released in Swift 4 Protocol Oriented Programming.  With this edition, we did a complete re-write and added a lot of new content.  

The Swift standard library is developed using protocol-oriented programming techniques, generics, and first-class value semantics; therefore, every Swift developer should understand these powerful concepts and how to take advantage of them in their application design.

This book will help you understand the differences between object-oriented programming and protocol-oriented programming. It will demonstrate how to work with protocol-oriented programming using real-world use cases. You will gain a solid knowledge of the various types that can be used in Swift and the differences between value and reference types. You will be taught how protocol-oriented programming techniques can be used to develop very flexible and easy-to-maintain code.

By the end of the book, you will have a thorough understanding of protocol- oriented programming and how to utilize it to build powerful and practical applications.

Some of the key areas covered is:
  *  Understand the differences between object-oriented programming and protocol-oriented programming
  *  Explore the different types that Swift offers and what pitfalls to avoid
  *  How Protocols and Generics are used in the Swift Standard library
  *  Delve into generics and see how to use them in a Protocol-Oriented design
  *  Learn how to implement Copy-On-Write within your custom types
  *  Implement several design patterns in a protocol-oriented way
  *  Design applications by prioritizing the protocol first and the implementation types second


Thursday, February 2, 2017

Getting started with the Kitura Stencil framework

In our last post we showed how to create REST based web services using Swift and IBM’s Kitura framework.  In this post we will show how to serve both static and dynamic web pages with Swift using the Kitura and the Kitura Stencil frameworks.  The Kitura framework, developed by IBM, is a light-weight, high-performance, web framework and server written in the Swift language.  The Kitura stencil framework allows us to separate our view component from the controller code when we are serving web pages.

If you are not familiar with what IBM is doing with server side Swift, I would recommend you visit their web site at https://developer.ibm.com/swift/.  One note, all code for this post was written and tested on an Ubuntu 16.10 laptop.  The code should also work on macOS but you may need to install other dependencies. 

We will start off by creating the project using the Swift Package Manager. To do this we will create a directory named kitura_web_page_sample and then initialize the project with the Swift package manager:

mkdir kitura_web_page_sample
cd kitura_web_page_sample
swift package init

The first thing we need to do is add the Kitura framework as a dependency for our project. We do this by adding the dependency to the Package.swift file.  The Package.swift file should have the following code in it:

import PackageDescription

let package = Package(
    name: "kitura_web_page_sample",
    dependencies: [
        .Package(url: "https://github.com/IBM-Swift/Kitura.git", majorVersion: 1, minor: 4)
    ]
)

Before we show how to use stencils and properly serve both static and dynamic web pages with Kitura, we will start off by showing what NOT to do.  Let’s create the main.swift file under the Sources directory and put the following code in it:

import Kitura

// Create a new router
let router = Router()

router.get("/dontdo") {
    request, response, next in
    response.send("<html><body>")
    response.send("<h1>Don't do this</h1>'")
    response.send("</body></html>")
    next()
}

// Add an HTTP server and connect it to the router
Kitura.addHTTPServer(onPort: 8090, with: router)

// Start the Kitura runloop (this call never returns)
Kitura.run()

The first line imports the Kitura framework so we can use it in our code.  Next, we create an instance of the Router class.  The Router class provides an interface for routing the incoming requests to the correct code.  This class lets us handle all standard REST request types. You can find the reference page for the Router class here:  http://ibm-swift.github.io/Kitura/Classes/Router.html#/s:FC6Kitura6Router3getFtGSqSS_7handlerGSaFzTCS_13RouterRequestCS_14RouterResponseFT_T__T___S0_

We use the get method to set up a router handler that will be invoked when an HTTP GET request comes in with a path pattern that matches the supplied path.  In this example, the path that we are matching against is “/donotdo” because we should not be serving web pages this way.  If a request does come in with the correct path, the code in the closure is called.  In our service, we send back a HTML page that displays the text “Don’t do this”.

We use the addHTTPServer(onPort:with:) to register the router.  The onPort parameter is the port number to bind the server too.  In this example, we will bind to port 8090.  This call only registers the server, it does not start listening until we call the run()  method in the last line.

Now let’s save the file and run Swift build from our project’s root directory.

If you receive an error that the compile could not find curl/curl.h, you will need to install the libcurl4-openssl-dev package (or any of the other three packages that provide the curl.h header file).  To do this run the following command:
sudo apt-get install libcurl4-openssl-dev

If everything compiles correctly we can run the application with the following command from the project’s root directory:

./.build/debug/kitura_web_page_sample

If everything starts up correctly, we can open any web browser and see the page by going to http://localhost:8090/donotdo. 

Now the question may be, why shouldn’t we do this.  It is good practice to always try to separate the view component from the controller.  With the previous code our view (HTML code) is embedded within our controller which means we will have to update the code every time the view changes.  This is definitely not ideal especially since the person that creates the view can be different from the person that writes the controller.

To separate the view from the controller we can use Kitura templates.  The Kitura template engine allows us to render web pages from static templates.  This allows us to update the view by updating the template rather than the controller code.  Let’s see how we can use the Kitura template engine.  The first thing we need to do is to update the dependencies for our project.  The following code shows the new Package.swift file with the updated dependencies.

import PackageDescription

let package = Package(
    name: "kitura_web_page_sample",
    dependencies: [
        .Package(url: "https://github.com/IBM-Swift/Kitura.git", majorVersion: 1, minor: 4),
        .Package(url: "https://github.com/IBM-Swift/Kitura-StencilTemplateEngine.git", majorVersion: 1, minor: 4)
    ]
)

Now let’s create a template.  Templates reside in a directory called Views off of the project’s root directory. The following command will create this directory:

mkdir Views

The stencil files use a file extension of .stencil.  Let’s create a stencil file named home.stencil and put the following code in it.
<html>
  <body>
    <h2>Hello Turtles</h1>
    <p>
  </body>
</html>

Notices that this stencil file contains standard HTML at this point.  To use this template, we need to import the Kitura Stencil framework into our code.  Add the following import to the main.swift file:

Import KituraStencil

Now we need to set the stencil engine right after we create the router.  The following code shows how to do this:

// Create a new router
let router = Router()

//Setup Stencil
router.setDefault(templateEngine: StencilTemplateEngine())



Finally we will create a router handler that will use the stencil.  Put the following code in the main.swift file right below the other router handler:

router.get("/home") {
    request, response, next in
    defer { next() }
    try response.render("home", context: [:])
}

Notice the try response.render(“home”, context: [:]) line in the router handler.  This line will look in the Views directory for a file named home.stencil and render the page from the template.  The context parameter is used to pass data to the template.  We will see how to use the context parameter a little later in this post but before we do that let’s see how we can use a template within another template.

There are times when we would like to use a standard header or footer for all web pages.  We really do not want to put this code in each template because then when someone wants to changes the header or footer we would have to make the changes to each template.  With the Kitura stencil framework we can embed one stencil within another.  Let’s see how this works by creating a simple header named header.stencil in the Views directory and put this single line of code in it:

<h1>Mega Turtles</h1>

We can now update the home.stencil file so it contains the following code:

<html>
  <body>
    {% include "header.stencil" %}
    <h2>Hello Turtles</h1>
    <p>
  </body>
</html>

Notice that we added the {% include “header.stencil” %} line to the file.  This line will search the Views directory for a file named header.stencil and embed the code from that file into this page.  If we build and run the application we will see that the Mega Turtles header is now at the top of the page.

When we refer to these files we refer to them as templates however you may be wondering why we use the .stencil extension.  This is because we are using the Stenciltemplate engine.  This stencil engine allows us to substitute template variables with actual values at runtime.  This allows us to create dynamic web pages.  We saw a basic example of this in the previous post where we added the header template to the page.

Let’s see how we can use the template engine to create dynamic pages.  The first thing we need to do is to create a new template.  Let’s create a template named list.stencil in the Views directory and put the following code in it.

<html>
  <body>
    {% include "header.stencil" %}
    There are {{ turtles.count }} turtles.
  </body>
</html>

Notice the new line in this file.  Before we explain this line, let’s look at the router handler that will use this template.

    router.get("/list") {        request, response, next in        defer { next() }        var context = [String: Any]()        context["turtles"] = turtleNames        try response.render("list", context: context)    }

Within this router handler, we define an array named turtleNames with four elements.  We also create a dictionary object named context.  This dictionary will contain the data for the template to use.  We add the turtleNames array to the context dictionary with a key of turtles and then include the context dictionary when we render the list template.
If we look back at the list template, we see that we use the turtle array like this: {{ turtles.count }}.  This code calls the count property on the array to print out the number 4 since there are four elements in our turtleNames array.
Now let’s change the list.stencil file so we will print out the list of turtle names.

<html>
  <body>
    There are {{ turtles.count }} turtles.
    <ul>
    {% for turtle in turtles %}
      <li> {{ turtle }} </li>
    {% endfor %}
    </ul>
  </body>
</html>

Notice the new code that is within the {% and %}.  The line with the for turtle in turtles creates a for loop to iterate though the turtles array.  We then display each element in the array with the {{ turtle }} line and end the for loop with the {% endfor %} line.

Here is the full listing of the main.swift file:

import Kitura
import KituraStencil

// Create a new router
let router = Router()

//Setup Stencil
router.setDefault(templateEngine: StencilTemplateEngine())

router.get("/dontdo") {
    request, response, next in
    response.send("<html><body>")
    response.send("<h1>Don't do this</h1>'")
    response.send("</body></html>")
    next()
}

router.get("/list") {
    request, response, next in
    defer { next() }
    var context = [String: Any]()
    let turtleNames = [
        "Donetello", "Leonardo", "Michelangelo","Raphael"
    ]

    context["turtles"] = turtleNames
    try response.render("list", context: context)
}

// Add an HTTP server and connect it to the router
Kitura.addHTTPServer(onPort: 8090, with: router)

// Start the Kitura runloop (this call never returns)
Kitura.run()

It is pretty easy to use the Kitura Stencil framework.  In future posts well will be expanding on this knowledge.