In the post Running Swift on Ubuntu Server (on VirtualBox) we installed swift on an Ubuntu Server 15.10 installed in VirtualBox virtual machine and then we have compiled our first swift program, naturally it was hello world.

This time we are going to use the Package Manager provided by Apple to create a real project.

Let’s start our virtual machine and login in it.

When the shell is ready issue the following command to create the directory structure for the HelloWorld project:

gigi@ubuntu1510:~$ mkdir HelloWorld; cd HelloWorld; mkdir sources

At this point we have to create the Package.swift file for our project. You can use your favourite editor, the file shall containing the following code:

import PackageDescription

let package = Package(
name: "HelloWorld"
)

swift_ubuntu_virtualbox
Now move into the sources directory

gigi@ubuntu1510:~/HelloWorld/ $ cd sources

and create the main.swift file containing the code

import Foundation
import Glibc
print("Hello World!")

Save the file and go back to the project root directory

gigi@ubuntu1510:~/HelloWorld/sources $ cd ..

It is time to build the HelloWorld executable

gigi@ubuntu1510:~/HelloWorld/ $ swift build

now your HelloWorld program should be built. Try running it, note that the “swift build” command creates a complete directry structure inside the root of your project. The directory is invisible, its name is .build. So issue the following command to execute your progam:

gigi@ubuntu1510:~/HelloWorld$ .build/debug/HelloWorld
Hello World!

Let’s add a new class to the project, go to the sources directory

gigi@ubuntu1510:~/HelloWorld/ $ cd sources

and create the classA.swift file with the following code:

import Foundation

class classA{
        var prop1: Int
        var prop2: Int

        init()
        {
                prop1 = 1
                prop2 = 2
        }

        init(val1: Int, val2:Int)
        {
                prop1 = val1
                prop2 = val2
        }
        func printClassA()
        {
                print("prop1 = \(prop1)")
                print("prop2 = \(prop2)")

        }
}

The above class have two initializers (which initiliaze the two properties) and a function which prints out the two properties.

Now modify again the main.swift file, the new content will look like the following:

import Foundation
import Glibc
var instance: classA = classA()
print("Hello World!")
instance.printClassA()

Move back to the project root

gigi@ubuntu1510:~/HelloWorld/sources $ cd ..

and build the executable

gigi@ubuntu1510:~/HelloWorld$ swift build
Compiling Swift Module 'HelloWorld' (2 sources)
Linking Executable:  .build/debug/HelloWorld
gigi@ubuntu1510:~/HelloWorld$

Run your application

gigi@ubuntu1510:~/HelloWorld$ .build/debug/HelloWorld
Hello World!
prop1 = 1
prop2 = 2

Really this is not a very complex application, but, at this point we are using the right tool to handle more complex projects.

Gg1