Writing Swift Programs on Linux

xc7-swiftlogo_2x1Swift Programming on Linux

The steps below walk you through the process of downloading, installing & using the Swift Programming language on Linux. For this I will be using Ubuntu Linux 14.04.3 LTS version.

Setup & Configuration

  1. Downloading Swift
    The first step is to download Swift from the link given below. Select the correct version of the OS.
    https://swift.org/download/#latest-development-snapshots
  2. Install clang
    The next step is to get hold of clang which is  a compiler front end for C,C++,Objective-C & Objective-C++. For more information on clang:
    https://en.wikipedia.org/wiki/Clang
    http://clang.llvm.org
    To install clang run the command:
    sudo apt-get install clang
  3. Extract the Swift files you downloaded and place them in a folder of your choice.
  4. Next we will add swift to our path. Do that by running the command:
    export PATH=/path to your swift folder/usr/bin/:”${PATH}”
  5. Verify whether it works by trying the following 2 commands
    which swift
    swift –version

Testing the REPL

  1. Next we try the REPL for swift. To invoke this just type the command:
    swift
  2. Write something like let myName : String = “Swift Code”
    and then hit enter.
  3. Follow it by print(myName) and then hit enter.
  4. You should see the output printed. This is a nice way to test individual Swift statements.

Creating a Single File Project

  1. To create a file based project:
    1. Create a folder of your choice, lets call it Hello World:mkdir HelloWorld
    2. Create a manifest file for the Package with the command: touch Package.swift
    3. The source files for all your projects must be in the Sources folder, let’s create that: mkdir Sources
    4. Create a file called main.swift using an editor of your choice. Place the statement print(“Hello, World”) in it.
    5. Step out of the sources folder and then run the command to build the project: swift build
    6. The executable will be inside a hidden folder called .build/debug
    7. The name of the executable will be the same as the name of the project folder.
    8. To run it simply type: .build/debug/HelloWorld

Creating a multi file project

  1. Create a folder of your choice, lets call it Hello World:mkdir CentigradeToFahrenheit
  2. Create a manifest file for the Package with the command: touch Package.swift
  3. The source files for all your projects must be in the Sources folder, let’s create that: mkdir Sources
  4. Create a file called converter.swift using an editor of your choice.
  5. Write the following code in it.:
    //note the code below is for demonstrating multi file projects & may not necessarily be accurate or correct
    func centigrade_to_fahrenheit(temperatureInCentigrade : Float) -> Float

    {
              return ((temperatureInCentigrade*9.0/5.0)+32.0)
    }
    func string_to_float(input : String) -> Float
    {
              var number : Float = 0.0;
              var result : Float = 0.0
              for charac in input.characters
              {
                        switch charac
                        {
                                  case “0”:
                                            number = 0.0;
                                  case “1”:
                                            number = 1.0;
                                  case “2”:
                                            number = 2.0;
                                  case “3”:
                                             number = 3.0;
                                  case “4”:
                                            number = 4.0;
                                  case “5”:
                                            number = 5.0;
                                  case “6”:
                                            number = 6.0;
                                  case “7”:
                                            number = 7.0;
                                  case “8”:
                                            number = 8.0;
                                  case “9”:
                                            number = 9.0;
                                  default:
                                            break
                        }
                        result = (result * 10.0) + number;
              }
              return result
    }
  6. Create a second file called main.swift
  7. Write the following code in it:
    if Process.arguments.count != 2
    {
              print(“USAGE: centigradeToFahrenheit 33.4”)
              print(“You are missing an argument”)
    }
    else
    {
              let temperatureInCentigrade = string_to_float(Process.arguments[1])
              print(“\(temperatureInCentigrade) is equal to \(centigrade_to_fahrenheit(temperatureInCentigrade))”)
    }
  8. Step out of the sources folder and then run the command to build the project: swift build
  9. The executable will be inside a hidden folder called .build/debug
  10. The name of the executable will be the same as the name of the project folder.
  11. To run it simply type: .build/debug/CentigradeToFahrenheit 100
    1. Try with different input values and no input value.
  12. That’s it. You are now ready to start typing code in Swift.

 

Clarifying Swift & Objective-C

swiftApple made a surprising announcement at the recent WWDC held between June 2-6 2014. While everyone was looking forward to the launch  of the new OS for both the Mobile as well as Mac platforms, Apple also announced a new programming language for developers. SWIFT.

It was described as Objective-C without C. Over the past few months I have gone over the features of the language & even converted many of the apps into Objective-C. While the initial learning curve is there, it is a fairly easy language to pick up. I will be going over a few interesting features of the language in this article. But what I will also be touching upon is the future & relevance of Objective-C.

Reduction in Lines of code: One of the first things that you will notice once you start programming in Swift is the reduction in the number of lines of code. Swift does away with the long syntax which you find in Objective-C. This makes the code look a lot more compact & less intimidating.

Lets take the example of creating an object in Swift & compare the syntax with that of Objective-C

Objective – C version: NSString *myString = [[NSString alloc] initWithString:@”This is a string”];

Swift version: var myString : String = String(“This is a string”)

As we can see, there is a great deal of simplicity that comes along. Reduction in the number of lines of code is of great importance to software developers. This means more compact code & improves readability. However, this comes at a price. While Objective-C code was more elaborate & did use many more lines of code it was far easier to understand by simply reading through it. In case of Swift the code will have to be complemented with details comments about what it does.

Single File: Another new feature there in Swift is the lack of header files. People coming from a Java background would find this familiar. The declaration of classes & implementation of its functions is done in .swift file now. This removes the necessity of having to import various header files. In case, certain frameworks need to be used all that needs to be done is to import that framework at the top of the file.

import framework

Replace the keyword framework with the name of the framework you wish to include.

Mixed Language Programming: Unlike Objective-C, Swift does not work well with other languages. In fact, Swift only works with Objective-C. So if you have any API’s or pieces of code that you have written in C or C++, you will have to create Objective-C wrapper classes for that C/C++ code so that you can incorporate it into your project.

This means that Objective-C is not going to be deprecated any time soon. Also, it will be equally important to learn Objective-C & can’t be ignored by people.

COMMON QUESTIONS:

– I already know Objective-C should I also learn Swift?
There is no pressing need to immediately learn Swift, though it would be a good idea to learn it anyways. None of the apps you have already made will stop working. However, you may come across code written in Swift or would need to incorporate programs written in Swift, so having knowledge of the same would be a good idea.

– I don’t know Swift or Objective-C which should I learn?
Again, as in the previous question knowing both is a really good idea. If you are confident that you will be making apps using Swift only, then you can learn just that for starters. If you feel that there is a good chance of having to read/modify or write Objective-C code then learning Objective-C before Swift makes more sense.

CONCLUSION: Swift is a very easy to use language & will sit nicely on familiar eyes. A lot of the code that will be written in the coming apps will definitely use Swift. However, this does not mean the end of the road for Objective-C. Nor does it mean that Objective-C will become redundant or obsolete. A developer can choose to use any of the languages to make the app. It will be nice for a new developer to first learn Objective-C & then move on to Swift as it will give the user a more all round understanding of the entire development framework .