Developing a Swift App

11 Feb 2015 9:54am, by

This is the first in a series of articles to help you learn Swift. In each article I’ll develop a complete app and the source code is on Github. We’ll start with a complete blank slate, assuming that you don’t know anything about Swift, or iOS development.

To compile and run Swift Apps you need a Mac running OS X 10.6 or later. You will also need to download and install a copy of Xcode 6, which is available free in the Mac App Store. It includes a simulator that is a software version of a specified iOS device. It’s a very convenient way to test your App so long as it doesn’t use hardware like the Camera. For that you need real hardware and if you want to run any App on your iOS device (iPhone or iPad) you will need to pay $99 each year to Apple to become a registered developer. This also lets you develop Apps and sell them or give them away free via the App Store. But let’s learn to walk first.

Some Background to Swift

Announced by Apple in June 2014, Swift became available to registered developers not long after. It’s a powerful programming language that draws the best bits from other programming languages like C#, Python, Google Go and others. I’ll explain what you need to know as we go along. Swift is a lot easier to read than Objective-C and has other advantages but remember that since 2008 developers have created millions of Apps using Objective-C.

About iOS

This is the operating system for iOS devices, it used to be called iPhone Operating System. Any App you develop must comply with iOS or when you start to run it, iOS will kill it. What that really means is your App must finish all it’s initialising and setting up within 17 seconds. In computing terms that’s a very long time.

We’re not going to worry about things like the accelerometers, cameras, GPS etc in this article. Consider the iPhone just as a simple display device that can respond when you touch it. Once you understand this then dealing with the rest of hardware isn’t so hard.

Architecture of an App

Xcode Front Screen
Lets start by creating our first Swift App. Open Xcode, click Create a New Project and select Single View Application then click the Next button. On the next screen I’ve called the App FirstApp and set the Organization Identifier to com.thenewstack. The language defaults to Swift and device to iPhone. On the screen after that select where you want the project created and Xcode will leave you in the main screen.

Xcode Select screen

The left column shows the project files. Click the right arrows so it opens up. The two under Products will show in red, meaning they’re missing until you do a build. Do this by clicking Product on the top menu then Build.

Xcode Project Files

I had my iPhone plugged in so it defaulted to that but you can specify the simulator iPhone model by clicking to the right of FirstApp > located just to the right of the Xcode Windows traffic lights.

Xcode top screen controls

After it’s successfully built you can run it by clicking the play button to the right of the green traffic light.

It doesn’t do very much because we’ve not written any code yet. This will be a quadratic equation solver. If you have a quadratic equation which describes a polynomial like a*x^2 + b*x + c, we want to figure out for a given set of variables a,b,c what the values are for x where the value of the quadratic is zero. Note to be quadratic, the value of a cannot be zero.

If you have trouble understanding this, a quadratic equation can be plotted as a curve on a chart and we are trying to work out where on the chart the curve crosses the x axis. Every point on the curve (y,x) is defined by y= a*x^2 + b*x + c, so when y is 0, x is ? The website will plot a curve so you can see what it looks like for any a,b and c parameters.

Now if you know your maths, you’ll know that there’s an equation that will solve this.

So our App will take in values for a,b and c and either solve it for x or tell us if it’s unsolvable. The +/- means that there could be two values in the answer. I.e. the curve loops and crosses the x axis in two places. That breaks down into these two equations.


Got that? No more maths I promise!

So our App will allow you to enter three values, then you hit a Solve It! button and it displays the answers.

For this we will use four controls. A Textedit field for entering a value, a button that you click to calculate, labels to show text and a TextArea to display the answers.

What is a StoryBoard and a Nib?

If you look at the list of files in Xcode on the left you’ll see LaunchScreen.xib and main.storyboard. If you right click on one of these files, a menu will appear and if you select Open As and then Source Code on the submenu, you’ll see that both files are XML. It’s a text file format that contains a hierarchy of items within it. Storyboards let you describe a series of View Controllers and how they connect to each other and is the best way to design a complicated App with lots of screens. A nib file lets you define one screen of controls and is called nib even though the extension is .xib.

LaunchScreen.nib is a splash screen, what you see when the App opens. It comprises two text strings. Open it using Open As but this time select Interface Builder XIB Document. You can see the strings and by double clicking on them get into edit mode and make changes.

Designing the App’s User Interface

Open Main.storyboard in the Interface Builder, you should see a rectangle with three icons in the centre. The area below the icons represents the screen area. Before we do anything else, let’s change its size to represent the model of iPhone.

Xcode storyboard designer

On the right of the screen you should see six icons. If there isn’t a right most column, click the View top menu then Utilities then Show Attributes Inspector. The first of the icons is looks like a sheet of paper with the top corner folded over, the next a circle containing a question mark. Select the fourth one, the downward pointing arrow. You should see Simulated Metrics and five combo boxes. Click Size and choose your phone. Mine is an iPhone 5 so I selected iPhone 4-inch. Changing that will adjust the central rectangle.

Now on the bottom right of the screen you’ll see a bunch of yellow circles. This is a toolbox of View Controllers and Views. A View is just another name for a control. Below the toolbox you should see a filter box. Type in the word Text in it and you’ll see that there are now just two items in the list. A Text Field and a Text View.

Drag the Text Field box onto the large empty rectangle maybe an inch from the top. Now drag two more and put them to the right of the first one, spacing them out so they occupy most of the screen. The designer is helpful and lets you line them up so they’re all level. Now drag a Text View onto the screen area, maybe an inch below the Text Fields. Use the drag points so you can stretch it to fit across the screen. You’ll see it full of Lorem ipsum text.

Next change the filter text to Label. Drag a label above each of the Text Fields, and one label just above the Text Area. Finally change the filter text to Button and add a button somewhere below the Text Fields and above the Text View.

You can build and run it but it doesn’t do anything and it doesn’t look great but we’ll fix that!

Make sure that the downward arrow icon (the Attributes Inspector) is highlighted in bold blue on the right hand side. Then when you select a control you get all the settings for that control. Select the first Label with your mouse. You should now see the word Label on the right and many different settings. The second line down is the text that the label shows when you select a label so select each one individually and change it to A, B or C. Then select the button and change the Button text to Solve It! If the button text vanishes, click on the right middle grab point and pull it to the right. Also select the Lorem ipsum label and change the text to the word Answer.

Now for Some Code

We have to get input from the Text Fields, do the calculation then update the Text Area. We connect visual controls to code using outlets or IBOutlet to give them their proper name. First lets view the code for the ViewController.swift file. On the left hand side make sure the project files are visible. If they aren’t select the first of the 8 icons, it looks like a folder.

We are going to add four IBOutlet variables, one for A,B and C and one for the TextView. Swift is an object oriented language and in the ViewController.swift file there is a class ViewController. We’ll add the four outlets just after the class.

class ViewController: UIViewController {

@IBOutlet var aTextField : UITextField
@IBOutlet var bTextField : UITextField
@IBOutlet var cTextField : UITextField
@IBOutlet var resultTextField : UITextView

Plus we’ll add a function. In Swift and most other programming languages, a function is a place to put common code, or just to put code that will do something notable. In the listing below this is what the code will look like for now. Swift functions are of the form func followed by a name then any input parameters and optionally a return value. None of the functions below return any values yet but we’ll use another one to do the donkey work later on.

The first two functions are standard ones that all ViewControllers start with. The third one is one I’ve added and has an @IBAction at the start. This is needed because when the Solve It! button is clicked, it calls this function. The glue that binds each of the Text Fields and Text View to the variables is called a connection. It’s a little fiddly but with practise it’ll become second nature.

Connecting Controls to Code

Select the Main.storyboard in the project file view so the form with the labels and Text Fields is visible. On the right hand column select the sixth icon, a circle containing an arrow pointing to the right and select the View Controller. You’ll see several sections but the one we want is the Outlets list which should be near the top. Click the circle to the right of the first item in the list which should say aTextField and drag it to the Text Field under A and let go.

Xcode connecting controls to code


You should now see the first Outlet has a shaded ellipse around aTextField and the circle is filled in.


Xcode after the connection

Repeat this for B and C and then drag the resultTextField to the Answer label. Finally look to the bottom of the right hand column and find Received Actions. Drag a line from the circle to the right of solveQuadratic to the Solve It! button. A floating menu will appear — look for Touch Up Inside and click it. When you click the Solve It button, it will call the solveQuadratic() function. At the moment that function doesn’t solve the problem, it just takes the three numbers entered and combines them one after another. If you enter 5, 6 and 7 and click Solve It!, the Answer becomes 567.

We are however well on the way to having a working app. There are a few issues to overcome: do the correct calculation, limit the input to numbers only and hide the keyboard when the Solve It button is clicked. Let’s limit the input to just numbers as currently it pops up the default keyboard with letters etc.

Select the A Text Field and click the Attribute Inspector icon (the 4th one). Look down the attributes and you’ll see a Keyboard Type combo. Click the combo and change it to Numbers and Punctuation keyboard as we’ll want numbers like 3.5 or -7. Unfortunately we also get a bunch of other punctuation chars as well. There are ways round this but too long to include in this tutorial.

Hiding the keyboard is easy. Just add this line to the solveQuadratic() function.

It tells the view to endEditing which closes the keyboard down.

Solving the Quadratic

We’ll create a function quadraticSolver which takes three doubles as input and returns a string with the answer. There are several possible answers.

  1. If a is zero then return a message “Please enter a non zero value for A”. We don’t want it to do divide by zeros.
  2. If b*b > 4*a*c then we get two values.
  3. If b*b equals 4*a*c then there’s only one answer as Sqrt(b*b-4*a*c) is zero so x = (-b )/2a.
  4. If b*b is less than 4*a*c then we are faced with taking the square root of a negative number. This takes us into the realm of complex numbers and we’ll ignore that option by just returning a message “The answer has complex number roots”.

Extracting the Numbers

The three numbers are entered as text and have to be converted to doubles. Swift has both Float and Double types for handling floating point numbers but I chose Doubles. The easiest way to do this is call the strtod function which is part of the C stdlib. Don’t worry about that just pass in the string and a nil for the second parameter. Now that we have three double values a,b and c we can call the quadraticSolver() function and return an answer.

The first line declares the function has the three input values which I’ve again called a,b and c and the last part of the declaration, i.e the -> String before the { declares that it returns a String. The first if does a check that a isn’t zero (or in this case very small or 0). Checking that a float or double variable is 0 or very near can have problems if you use “if value == 0.0” and the value is very small but not 0. This check catches that and the abs() function call makes sure that it works with very small negative numbers as well.

If statements are similar to other languages like C,C++,C# or Java except (a) you don’t need brackets round them and it always needs braces { … } for the statement that will run if the condition is true and (b) single line ifs without braces are not allowed.

The values of b*b- (4*a*c) is now calculated and stored in the variable b2_4ac. Note that Swift really likes to have spaces around equals (= or ==) so if you get an error next to an – it’s likely that.

The let statement declares an immutable variable, ie once you assign a value to it, it can never be altered. If you need a mutable variable, ie one that can have its value changed, declare it with var instead of let. All the variables used in this function will never need to be changed so let was used.

Like in C etc, the return statement exits the function and returns a value of the spcified type.

The statement “There is one answer \(result)” converts the variable result into a string and inserts it in to the full string. This is called String Interpolation and used again later on in the function. Also the \n in “Root 1 = \(root1)\nRoot 2 = \(root2)” breaks this into two lines.

You might spot that the call to this function looks a bit odd.

Why is it

instead of

This is a quirk of Swift which apparently originates in Objective-C. Swift allows named parameters (the b: and c:) but only the first parameter gets a default name and the rest have to be explicitly named.

Values to Try

Try a=1, b=8 and c= 16, it should give one answer -4. While a=1, b=-2 and c=-3 should give 3 and -1 as the roots. For a complex number use a=3, b= 1 and c= 2.

Feature image via Flickr Creative Commons.

A newsletter digest of the week’s most important stories & analyses.