Learning Swift: The Basics


This article is part of the Learning Swift series.

Before you can sell your app and become a hundredaire, there are some programming basics you will need to know. These concepts are common to pretty much every modern language, so once you have them down for one, you can apply them to another.

Variables & constants

When building an application, you will often be dealing with some sort of data, or information, that needs to pass from one part of the application to another. This is done through the use of variables and constants.

Variables are dynamic containers. The contents of variables can be added to, removed, and changed at any point in your application. In some languages, you have a lot of flexibility with variables and constants. In PHP, for example, variables can be created at any time, and can contain a mix of different data types (for example, integers, decimals, arrays, objects, etc). In Objective C, the predecessor to Swift, variables were inflexible, and we’re strongly defined before any data ever made its way into them. This is known as data typing. When creating a container to hold data, like a variable, the variable is given a definition of what type of data it is allowed to contain. If data is placed into the variable that doesn’t conform to the definition, the compiler will throw a fatal error and your application will not build.

Swift provides a nice middle ground. In Swift, variables are typed, but the typing can be done subjectively by the compiler. In Swift, you can simply define a variable by providing its initial value:

 var myVariable = “This is a string typed variable”
var myInteger = 10 // This is an integer-typed variable
var myDecimal = 3.14 // This is a float (decimal) typed variable

Compare this to other modern languages:

PHP:

 $myVariable = “This is a string typed variable”;
$myInteger = 10; // This is an integer-typed variable.
$myDecimal = 3.14; // This is a float (decimal) typed variable.

Ruby:

 myVariable = “This is a string typed variable”
myInteger = 10 // This is an integer-typed variable.
myDecimal = 3.14 // This is a float (decimal) typed variable.

Constants are intended to be, well, constant. The value you place into a constant cannot be changed, and can only be read from or deleted entirely. In some languages, constants have a special syntax. For example, in PHP, you first define a constant (the convention in PHP is to name constants in uppercase), then access it by placing the constant into an expression.

For example:

 define(‘APP_VERSION’, ‘1.2.3');
sprintf(‘Welcome to version %s of the software.’, APP_VERSION);

In Swift, constants are defined using the keyword ‘let’. The above example would look like this:

 let app_version = ‘1.2.3'
println(“Welcome to version \(app_version)of the software.”)

In The Swift Programming Guide and some of the sample applications available, it appears that the use of constants is preferred whenever possible over variables. The guide says, in a note,

If a stored value in your code is not going to change, always declare a constant the let keyword. Use variables only for storing values that need to be able to change.

This makes sense when you consider that Swift, like Objective C, is a compiled language. As a result, it has a much greater need to manage memory than an interpreted language like PHP, which dynamically controls the amount of memory in use.

Data types

As I mentioned in the Variables section, there are a number of different types of data. In general, data types deal with strings (single or multiple alphanumeric characters, such as a sentence) and numbers (integers and decimals). There are some additional special types for other kinds of data, such as TRUE/FALSE conditions. In Swift, there are a number of different data types. They are:

Numeric data types

  • Integer. These store whole numbers, such as 5, -42, or 32000.
  • Float. These store decimal numbers, such as 3.1415 or -2.76.

Alphanumeric data types

  • Character. A single alphanumeric character, for example ‘a’ or ‘6' (note the quotation marks).
  • String. A string is a collection of characters, for example ‘Hello world.’ String variables can have a number of operations done to them such as appending, pretending, and concatinating, but they cannot be used in arithmetic operations.

Other data types

  • Boolean. This is a TRUE/FALSE data type, and can only contain one of those two values. In some languages, such as PHP, an alias of 1 is set up for TRUE, and 0 for FALSE.
  • Array. An array is a collection of independent pieces of data. For example, you might have an array of strings that make up a collection of fruits
 var fruits = [
‘apple’,
‘banana’,
‘orange’,
]

Or, you might store the progression of the Fibbionaci sequence within an array

 let fibbionaci = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144]

Arrays are really useful for moving collections of data around your application. For example, you might create an array that has a list of RSS feeds in your application.

  • Dictionary. A dictionary is a special type of array in Swift that helps index the data. An example of a dictionary is given in The Swift Programming Language:
 var occupations = [
“Malcolm”: “Captain”,
“Kaylee”: “Mechanic”,
“Jayne”: “Public Relations”,
]

Conditionals and loops (control flow)

There are times when you are putting together an application when the logic you are building is dependent on either the state of a variable or constant, or needs to loop through a collection of data, performing the same task multiple times.

if/else/switch

‘If,’ ‘else,’ ‘else if’, and ‘switch’ are used for examining data and running a set of instructions based on the state of that data. For example, continuing the versioning above, you might run a different set of instructions based on the version of the software — for example during an upgrade. In PHP, this would look like the following:

 // call a function to get the current installed version
$current_version = getCurrentVersionFromDB();
If ($currentversion < 1.0) {
addNewDBtable(‘new_featurestore’);
}

The syntax in Swift is virtually identical:

 // call a function to get the current installed version
let current_version = getCurrentVersion()
if current_version< 1.0 {
addNewDBTable(‘new_featurestore’)
}

For longer or re complicated conditionals, it’s recommended to use switch instead of else, for reasons of both performance and code legibility. This looks something like the following:

 switch let current_version = getCurrentVersion() {
case ‘0.8.0':
// add new DB table.

case ‘0.9.0':
// do something else.

case ‘0.9.1':
// a minor change

case ‘1.0.0':
// some other change.

default:
return false
}

for/while

The conditionals ‘for’, ‘for-in’, and ‘while’, and ‘do-while’ are used for looping through sets of data. This saves you a lot of time coding when you know you will be running a repetitive task against a group of data.

The ‘for’ conditional is used when you know your range, or are working with a known set of data. For example, from the Swift language documentation:

 let individualScores = [75, 43, 103, 87, 12]
var teamScore = 0
for score in individualScores {
if score > 50 {
teamScore += 3
} else {
teamScore += 1
}
}
teamScore // teamscore is 11.

The ‘while’ conditional is used for as long as a given condition is true. For example, from the Swift documentation:

 var square = 0
var diceRoll = 0
while square < finalSquare {
// roll the dice
if ++diceRoll == 7 { diceRoll = 1 }
// move by the rolled amount
square += diceRoll
if square < board.count {
// if we are still on the board, move up or down for a snake or a ladder
square += board[square]
}
}
println(“Game over!”)

Operators

Operators are special characters used in programming languages to check, change, compare, or modify values. These are:

Assignment operator (=). This takes the element on the left of the equals sign, and assigns it the value to the right. For example,

let meaning_of_life = 42

This assigns the integer value 42 to the constant meaning_of_life. When you later access the constant meaning_of_life, it will return the value of 42.

Arithmetic operators. These perform arithmetic operations on the elements around them. The operators are + (addition), — (subtraction), * (multiplication), and / (division). For example,

let the_question = 6 * 9

When you later access the constant the_question, it will return the value 54.

The one oddity within the arithmetic operators is the + operator. What stands out about this operator is that it can also be used on string elements. For example, if you wanted to add a variable name into a printed string statement to personalize a Hello, you could do the following:

 var name = “Darren”
println(“Hello “ + name + “, how are you today?”)
// Prints “Hello Darren, how are you today?”

Remainder operator (%). This operator calculates how many multiples of the number on the right will fit into the number on the left, and then returns the remainder. In some languages, this operator is known as the modulus. For example:

 var remainder = 42 % 5
// 5 fits into 42 8 times, and leaves a remainder of 2.
println (remainder) // prints out 2

Increment and decrement operators. These operators are used for increasing or decreasing the value of an integer element by 1. Generally, these operators are used when you need to include a counter in a loop.

In Swift, these operators have to different ways of working, depending on where they are in relation to the element. If the operators are placed before the element, the counter has immediate effect. For example:

 var a = 0
let b = ++a // a and b are now both equal to 1.

If the operators are placed after the element, the counter takes effect last. For example:

 var a = 0
let b = a++ // a is now equal to 1, but b is equal to the pre-increment value of 0

The Swift documentation recommends the use of ++variable over the use of variable++, because it better matches what most people would expect from a counter.

Compound assignment operators. These allow a new value to be appended to an existing variable, and exist primarily as a shorthand. For example, if you wanted to add 2 to the existing variable a, you would write the following:

 var a = 1
a += 2 // shorthand for a = a + 2
println(a) // Prints the number 3

Comparison operators. These are used to compare the value of one variable or constant to another. These are often used within conditionals, and you’ve already seen these operators in action. In short, the operators are:

  • equal to (a == b)
  • not equal to ( a != b)
  • greater than ( a > b)
  • greater than or equal to (a >= b)
  • less than (a
  • less than or equal to ( a

There are also two identity operators, which test to see if the variables/constants being compared refer to the same object instance. These operators are === (identical) and !== (not identical).

Range operators. These allow you to test a variable or constant for a range of values. These are most often used in the context of a loop, to match the value of a counter. There are also two states to the range operators. Three periods (…) takes both the first and last value of the range; for example 1…5 will count from 1 to 5. Two periods followed by a less than sign (..<) will only take the values between the range; for example 1..<5 will count from 2 to 4.

 for index in 1…5 {
println(“\(index) times 5 is \(index * 5)”)
}
// 1 times 5 is 5
// 2 times 5 is 10
// 3 times 5 is 15
// 4 times 5 is 20
// 5 times 5 is 2

for index in 1..<5 {
println(“\(index) times 5 is \(index * 5)”)
}
// 2 times 5 is 10
// 3 times 5 is 15
// 4 times 5 is 20

Logical operators. These are used for examining logical boolean conditions, such as AND (&&), OR (||), and NOT (!). For example, if I want to check if my Infinite Improbability drive is enabled before seeing if I can move in the universe, I might write the following:

 var ship = Ship()
let infinite_improbability = checkDriveStatus()
// returns FALSE; drive is off.
let button_pressed = didIPressTheButton()

// If our drive is enabled, and the button was pressed, engage the drive!
if infinite_improbability && button_pressed {
ship.shape = “Whale”
ship.location = ship.moveRandomly()
// If the drive is not engaged, or the button wasn’t pressed, do nothing!
} else if !infinite_improbability || !button_pressed {
println(“We’re not going anywhere!”)
}

Functions

An application is, generally, actually a collection of several smaller applications, called functions. Functions are mini-programs that live within your application to perform very specific tasks. For example, in your email client, a function exists that connects to your mail server and asks if there are any new messages. If there are, it will pass the work on to a different function that downloads the mail to your computer. Yet another function exists that displays the new messages in your mail client, so you can read them.

In PHP, functions are created fairly simply — you declare a function with the ‘function’ keyword and assign any parameters as part of that function definition. For example, if I wanted to create a function to authenticate a user against the database, my function might look like this:

 function authenticate_user($username = NULL, $password = NULL) {
$db = new Database();
// Query the database and fetch results
$db->query(‘select uid from user where username=’%s’ and password=’%s’, $username, $password);
$user = $db->fetchRow();

// Check to see if we got back a valid user id
if (isset($user[‘uid’]) && $user[‘uid’]<> 0)) {
return $user;
}
return FALSE;
}

In this function, you can see we have parameters ($username and $password) that are passed into the function, and a return value (indicated by the keyword ‘return’) that either contains the user id or a boolean FALSE value.

In Swift, a function call is very similar. You supply it with parameters and specify a return value. However, with Swift, it is mandatory that you specify the types of both the parameters and return values. The same function definition written in Swift would look like this:

 func authenticate_user(username: String, password: String) -> Any {
// run through steps to authenticate, return either FALSE or a user object.
}

There is much more to Swift than just this basic primer, but this should hopefully give you enough background to be able to follow along with further posts here. As always, if you have any questions, drop me a line at @staticred on Twitter!

Originally posted at Learning Swift.

Did you enjoy this article? Purchase it in iBooks.

Photo by Flickr user Julia P, used under Creative Commons