Variables – The Basics

205 0

Yes this is a very basic introduction, but it all has to start somewhere and there maybe people new to programming and the concepts. If you feel this article is below you then please skip it, but there are a few things worth noting in the new Swift language even for us seasoned developers.

We shall begin…

Everything starts from simple small pieces of information and works upwards, from a simple ‘Hello!’ printed to the screen in a terminal to a complex 3D game, these simple pieces are most likely going to be variables, there are many different types but the basic principles of creating and using them are the same. Variables are the very DNA of our applications, without them we are just shouting Hello World! In a standard font and not making it on the App store.

Variables are defined, used and changed on the fly unless they are constants. For example a game score starts with a number 0 and if you are good at the game it goes up! Or maybe it is a string holding the name of a player, this might be a constant if the player never changes. What about information that is more than one item, then it’s Arrays or Dictionaries that we will talk about in the future.

In Swift like other languages there are some rules to follow, here are the common ones you need to know to get started, firstly there are two basic types; Standard Variables and Constants

Standard Variables

  • They must be defined before they can be used, if you try to use one before defining it the compiler will be unhappy, you will be unhappy, the application might have a runtime error and your wages check might be $undefined. No Pizza for you!
  • You can change their values when you want but remember a string is a string and an integer is an integer. If you want to switch them around then you’ll have to do it with code.
  • Whilst we can specify the type of the variable, the Swift compiler is actually smart enough to figure it out for us using something called Type Inference. There is an exception here though, if you define a variable but give it a value later then you should specify the type at definition so the compiler knows what it will hold later.
  • If you try to do something with a variable of a certain type that makes no sense then the compiler will try and help you out by slapping your wrist and asking you to reconsider.

So lets create some variables!

To define a new variable we place var in front of the variable name and after it a colon followed by the type.

var myName: String

Now let’s populate the variable with a value

myName = “Peter”

Assuming you want to set the value at the time you create the variable then there is a much better and shorter way to do the above whilst taking advantage of Type Inference

var myName = “Peter”

Remember the compiler is smart enough to see that the value is a string and set the type for us, I just wanted to show you both ways so you’ll recognize them out there in the World.

Now what if we want to change the value of the variable? We do so but without using var again because the variable has already been defined.

myName = “Peter Witham”

Constant Variables

  • They follow many of the same rules as standard variables EXCEPT you can only set their value once.
  • You can set the value of a constant later after defining it if you want, this will help save a little memory until the variable is needed, but again remember you can only SET IT ONCE

We tell Swift that we want to create a constant by using the let keyword instead of var

let myName = “Peter”
let mySiteIsHelpful = true

mySiteIsHelpful will be seen as a Bool by Swift and that means it is either true or false. If you should try and assign a new value to a constant then you will get a nasty error, you have been warned!

Now Some Usage Examples

Here is an example of how you can create and use two variables inside a string, note that we can define more than one variable per line by seperating them with a comma

let firstName = “Peter”, lastName = “Witham”
let fullName = “Hello, my name is \(firstName) \(lastName), pleased to meet you!”

So to break this down we first create the firstName and lastName variables and give them values. Then we create another variable called fullName and assign its value by telling Swift we want a string that contains parts of a string and the value of the two variables. We indicate where we want the variables values to appear value with ()

The end result would actually be the same as saying

let fullName = “Hello, my name is Peter Witham, pleased to meet you!”

Another example would be using math in a string and performing a calculation of the two variable values.

var a=10, b=5
let addBothResult = “\(a) plus \(b) equals \(a+b)”

How about a collection of data in an Array

var seasons = [“Winter”, “Summer”, “Fall”, “Spring”]

Now lets use the println function to display each season

for season in seasons {
    println(“Season Name: \(season)”)

Alternatively let us get at the second item in the Array by using it’s index. Arrays are what we call a ‘zero based index’ meaning the first item is actually at index 0. So to get at the second element we would use the following

println("Season 2 is: \(seasons[1]))

So there is a basic introduction to Variables in Swift.


This would be a good time to mention that if you have access to Xcode 6 the new playground features are ideal for learning and playing with everything we have discussed so far and going forward.

There are many different types of variables, far to many to list here right now. Instead I suggest you check out the available documentation at the Apple Developer Site or the Xcode help files. I know this is a very basic introduction, but we have to get the syntax foundations out of the way. I would suggest not worrying about learning all the different types ahead of time, instead get down the basic ones and learn the others as you need them in your code.