Getting Started with Swift

In order to get started with creating programs in Swift, software is needed to facilitate the writing and compiling of a program. Writing a program in Swift can be done in a simple text editor, however, using an IDE, or Integrated Development Environment, can have many benefits. An IDE not only provides a means to write a program, it may also include features such as code completion, where it offers suggestions to complete a line of code, based on what has been typed so far. This is particularly useful if you are new to a programming language or, starting programming for the first time.

In order for a program in Swift to run, it must first be compiled. This is where a program is converted into a form that a computer can read. Some IDEs incorporate a compiler so that one does not have to be installed separately. Xcode is an example of an IDE that provides a means to write, compile and run a program written in the Swift programming language. As Apple provide Xcode for free on macOS, it is a popular choice, however, it isn't the only option.

To aid in the writing of a program, many IDEs, including Xcode, colour code various aspects of the program to make it more readable, as well as easier to maintain and troubleshoot.

Code Commenting

When programming in any language it is useful to add comments to the code to describe what is happening and why. This is useful when the code is revisited at a later date to make enhancements, or for debugging purposes. There are two ways of adding comments to Swift code. A single line comment starts with two '//'.

// This is a single line comment.

A multi-line comment starts with '/*' and ends with '*/'.

/* This
is
a
multi-line
comment */

First Swift Program

As well as being able to write complete applications using the Xcode IDE, it also provides a means to test Swift code using what it calls a 'Playground'. There are also online Swift compilers, such as the one provided by JDoodle.

The Swift code written below simply displays the words ‘Hello World!’ out to the screen.

print("Hello world")

The method for running the program will vary depending on the IDE being used. For an Xcode Playground, it is simply a matter of pressing the play icon and for JDoodle, there is an 'Execute' button to achieve the same result.