Switching to Swift

This week I seriously started learning Swift. Swift is a novel programming language developed by Apple to replace Objective-C. I already like it and I definitely enjoy the learning process. Some iOS developers I know are talking about how they love Swift. I am not there yet, although I have found three things that may ignite my love.

Playgrounds

I am starting to appreciate Playgrounds. It allows you to run individual lines of Swift code. After a bit of a rough start I now understand how to make it work. The great thing about running code line by line is that you can see all the intermediate results and really gain a deep understanding of what each line is doing. I am thoroughly familiar with this concept through my extensive use of Mathematica (presently more often referred to as the Wolfram Language). What to me is a bit unsettling is the following. If you want to have Mathematica execute a line of code, you select the proper cell and you hit Shift + Return. A Playground decides for itself when it starts executing your code. That does not feel right to me. I would prefer it if the system is doing code completion and checking for errors while I am typing, and only runs when I tell it to run. Maybe I just have to get used to it.

Functions

One thing I already really appreciate is the way functions are used. There is no distinction in Swift between methods (functions that belong to a class) and functions proper. I am used to writing methods in Objective-C and functions in C. I use a lot of C functions because I often want to apply mathematical formulas to my data. For example, if I want to calculate a distance from two other parameters, the function declaration in C looks something like this:

float myDistanceFormula(float firstParameter, float secondParameter);

And when I use this function somewhere else in my code, it looks like:

float distance = myDistanceFormula(1.0, 2.0);

Even though I wrote the code myself, I often can not remember what the parameters of that function actually mean. I have to keep going back to the function declaration to be reminded of their meaning. That has become much easier in Swift. The (combined) function declaration and implementation looks like:

func distanceFunction(firstParameter firstParameter: Double, secondParameter: Double) -> Double {
    return firstParameter * secondParameter
}

When I use this function somewhere else in my code, I can actually see the names of the parameters:

let distance = distanceFunction(firstParameter:5.0, secondParameter:2.0)

I am a big fan of the verbose nature of Objective-C and I am happy that it is preserved in Swift. And now that we are on the topic, I want to publicly thank the person who came up with code completion. I salute you!

Another big improvement has to do with return values. C functions can only return one value and that is often not what I want. I deal with a lot of functions whose output represent physical values. I like it if the accompanying estimated error is also part of the output. For example, a distance of 1.2 ± 0.2 meter. In Swift you can define a tuple as output that can contain multiple values. And of course you can give each of these output variables a name, so the resulting code is extremely easy to read.

Optionals

This is a very interesting concept built into the heart of Swift. An optional either has a value of a specific type, or no value exists at all (also referred to as nil). So for example if I want to get the present temperature in Amsterdam from a source on the internet, there is no guarantee that I will actually get a response.

let temperature: Double? = getTemperatureFromInternet(url: http://www.bbc.com/weather/2759794)

The optional nature is denoted by the question mark behind the type indicator and is pronounced as “optional double”. If all goes well, the variable has a specific value of type Double, for example 22.3 degrees Celsius. In case of a bad connection or a server malfunction, the temperature value does not resort to a default value (usually 0.0) but it explicitly tells us it has no value. The temperature is simply nil. It took me some time to grasp the concept and get familiar with its use, but I understand and appreciate it now. And I will probably use it often.

Final thought

I have dabbled in Swift a few times earlier since Apple announced it in June 2014. But now I have made a decision to graduate from the classics C and Objective-C to the modern Swift language. I have now officially switched.

>  You can sign up for my newsletter here.

4 thoughts on “Switching to Swift

  1. Hello! I started with Swift about the same time that you did, and love it! In addition to returning tuples, I am pleased with the notion of the ‘guard’ statement to ensure routines that can return correct results. I have been taking the “nano-degree” classes offered by Udacity, but I keep getting distracted by geometry tasks that I want to be able to do. Thank you for the details on the Core Image Framework.

    I have books on OpenCV, and ImageJ, but haven’t spent any time with them. Have you heard of anything similar being ported to the Swift world?

    Paul

    1. What geometry tasks are you trying to do? Maybe I can give you some pointers.

      I am somewhat familiar with OpenCV. It is written in C++, and that is why I have always struggled with it. As far as I know, no-one has rewritten OpenCV in Swift yet.

      1. I could use some pointers. I believe that I am writing good code, but am doing that in a vacuum, which isn’t healthy. I have a repository at: https://github.com/CeranPaul/SketchCurves for 2D building blocks. Feedback would be appreciated!

        I spent time yesterday reading up on Google’s Project Tango, and Intel’s camera package. Hope that continues to progress!

      2. What specific geometrical concepts are you grappling with? My general advice is usually to learn from the best math teacher on the web: Norman Wildberger via his YouTube channel https://www.youtube.com/user/njwildberger

        I also follow the depth sensing camera developments with great interest. My own approach is different though; I only need a standard camera without any extra hardware like an infrared projector, or a laser. (Stay tuned for details.)

        I will comment on your code on GitHub.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s