Variables, Constants, & Data Types

Free iOS Development Tutorial

This exercise is excerpted from Noble Desktop’s past app development training materials and is compatible with iOS updates through 2021. To learn current skills in web development, check out our coding bootcamps in NYC and live online.

Note: These materials are provided to give prospective students a sense of how we structure our class exercises and supplementary materials. During the course, you will get access to the accompanying class files, live instructor demonstrations, and hands-on instruction.

Topics covered in this iOS Development tutorial:

Declaring variables, Updating variables, Declaring constants, Data types, Type inference, String concatenation, Assignment operators, In-line multiple declaration

Exercise Overview

In this exercise we’ll start off with the most foundational programming concepts: variables and constants, which are containers that store various types of data. You’ll also learn how to concatenate (or put together) two strings.

Getting Started

You’ll write your code in an interactive environment called a Playground. In this Xcode environment the code updates in real time. It’s the perfect place to play around with Swift code and learn its syntax.

  1. Launch Xcode.

  2. Go to File > New > Playground.

  3. Under iOS, select Blank.

  4. Click Next.

  5. Navigate into Desktop > Class Files > yourname-iOS App Dev 1 Class.

  6. Save as: Swift Basics.playground

  7. Click Create.

    NOTE: If you get a prompt asking if you want to Enable Developer Mode, click Enable. It will ask for the admin username and password. If you’re in a class, have the instructor enter the password.

Line Numbers

A useful feature of Xcode is line numbers. It helps you to keep organized and refer back to previous code when needed. If you don’t see line numbers to the left of the code, follow the steps below:

  1. Go to Xcode > Preferences.
  2. Click the Text Editing tab.
  3. Make sure you are in the Editing section.
  4. Next to Show, check Line numbers.

Declaring Variables

Variables are containers used to store data which can then be accessed at another point. They are similar to the memory feature (M+) old calculators had to store a result, which could be used later in a new calculation. The first thing we need to do is declare a variable. This is the initial setup in which we will be specifying the type of information the variable will be storing. The type is important because each different data type takes a specific amount of memory. Variables always start with var followed by a space, then the name of the variable.

  1. In your new Playground file, delete all the code that’s there.

  2. Type the following code as shown in bold:
    var numberOfVerses
    

    NOTE: We are using the typing convention called camelCase, in which the name (in this case numberOfVerses) starts with a lowercase letter and each subsequent word in the name starts with a capital letter. There are no spaces between the words. camelCasing is not required but it’s a convention commonly used to make code more readable.

  3. To get rid of the error, let’s give the variable a value. Add the code shown in bold:
    var numberOfVerses: Int = 4
    

    The equals sign (=) is an assignment operator and sets the value of numberOfVerses to the number 4. : Int is a type annotation, which tells Swift that we are assigning a number, or integer. We’ll take a closer look at type annotation and data types later in this exercise.

  4. Now that you’ve declared a variable, you can use it. Type the bold code:
    var numberOfVerses: Int = 4
    
    print("This song has \(numberOfVerses) verses")
    
  5. Let’s break that down:

    • We just did something called string interpolation. This is a fancy way of saying we are using the variable name as a placeholder inside a longer string of characters. Swift will find the variable’s value and replace the variable name with its value.
    • We are using the print function (an action that Apple coded for us) which prints the result of the string interpolation to the sidebar on the right.
    • Any time you want to use or convert your variable within the context of a function, you use \(nameOfVariable).
  6. On the right of Xcode is the Playground results sidebar. This is where the results of the code you type in Playground automatically appear. Notice our function has printed out: This song has 4 verses\n

    New Line Characters

    As of iOS9, Xcode Playground adds the new line character \n at the end of printed lines by default. If you want to print without it you can add , terminator: "" at the end of the print function as shown below:

    print("Some message here", terminator: "")
    
  7. Add the bold code to get rid of the \n:

    print("This song has \(numberOfVerses) verses", terminator: "")
    

Updating a Variable

Let’s try changing the value of our numberOfVerses variable. All you have to do to change the value of a variable is type the variable name followed by an equals sign and the new value. Variables are considered mutable because you can mutate, or alter their value.

  1. Add the following bold code to change the value to 5:
    print("This song has \(numberOfVerses) verses", terminator: "")
    
    numberOfVerses = 5
    

    Notice that we have not used the keyword var here. This is because the numberOfVerses was previously declared.

  2. Let’s see the value print out in our sentence. Copy the entire print function.

  3. Paste it below, as shown:
    print("This song has \(numberOfVerses) verses", terminator: "")
    
    numberOfVerses = 5
    
    print("This song has \(numberOfVerses) verses", terminator: "")
    
  4. Take a look on the right of Xcode and you should see: This song has 5 verses

    So now you’ve declared a variable, used it, updated it, and reused it.

Adding Another Variable

Let’s add a new variable.

  1. At the bottom of Xcode, add:
    var numberOfTimesHeardToday: Int = 7
    
  2. Right off the bat, let’s change the value from 7 to 5:

    var numberOfTimesHeardToday: Int = 7
    numberOfTimesHeardToday = 5
    
  3. Let’s use string interpolation to include this variable inside the print function. Type the following code shown in bold:

    var numberOfTimesHeardToday: Int = 7
    numberOfTimesHeardToday = 5
    
    print("I have heard this song \(numberOfTimesHeardToday) times today")
    

    NOTE: For now we will ignore the \n and not add the terminator code. It’s up to you if you’d prefer to continue adding the terminator code.

  4. On the right of Xcode, you should see: I have heard this song 5 times today

Declaring a Constant

Constants work in exactly the same way variables do except that once they have been initialized to a given value, they cannot be updated. That’s why they’re called constants. Constants are declared just like variables except the keyword let is used instead of var. Constants are defined as immutable, that is, they cannot be changed.

The number of verses in our song is going to remain at 4, so it would make more sense for us to change numberOfVerses to a constant.

  1. Let’s try changing it by replacing var with let:
    let numberOfVerses: Int = 4
    
  2. Notice a red alert sign red circle error icon appears to the left of numberOfVerses = 5. Click it.

    The error says, Cannot assign to value: 'numberOfVerses' is a 'let' constant. This error is happening because now that you’ve made numberOfVerses a constant, you can’t change the value, which is what numberOfVerses = 5 is trying to do.

  3. Go ahead and delete the following lines, because you don’t need them anymore:

    numberOfVerses = 5
    
    print("This song has \(numberOfVerses) verses")
    

Data Types

You’ve specified both the numberOfVerses constant and numberOfTimesHeardToday variable to be integer (Int) data types. Type annotations, such as Int, tell the variable or constant what type of data it is. The available data types are listed below:

Data Type Use Example
String A set of text characters Names
Int Whole numbers (no decimal points) Age, Counters, etc.
Float Numbers with a decimal point (6 decimal places) Currency
Double Numbers with a decimal point of higher precision (15 decimal places) Geographical coordinates with 7 decimals
Boolean Values that are either true or false Yes/No question
  1. You’ve actually already created a string earlier in this exercise. The text in double quotes inside the print function is a string. Let’s add a variable with a string value. At the bottom of Xcode, type:

    var songName: String = "Comfortably Numb"
    
  2. As you’ve done before, put it in a sentence by typing:

    var songName: String = "Comfortably Numb"
    
    print("This song is called \(songName)")
    
  3. It prints: This song is called Comfortably Numb. Once again, you’ve used string interpolation to create a new string with a variable.

  4. Let’s declare a Float. At the bottom of Xcode, type:

    print("This song is called \(songName)")
    
    var songRating: Float = 7.5
    
  5. A Double is similar to a Float, but has higher precision because it can hold more digits. Apple recommends using Doubles (and if you don’t specify otherwise, Swift will automatically assign it to numbers with decimals). Let’s go ahead and make the change. Doubles are used in the same way as Floats, so you can change the Float into a Double by simply replacing the type.

  6. Change the data type to Double and print a new string as shown below:

    var songRating: Double = 7.5
    print("Out of 10, this song is a \(songRating)")
    
  7. On the right of Xcode, you should see: Out of 10, this song is a 7.5

  8. Next, you’ll add a Boolean. Create a variable called iAmInHere and assign the value of true, then print it as shown below in bold:

    print("Out of 10, this song is a \(songRating)")
    
    var iAmInHere: Bool = true
    print("It is \(iAmInHere) I am in here")
    
  9. On the right, you should see the confirmation: It is true I am in here

Type Inference

Swift has a nifty trick that allows us to do without type annotation in certain occasions when we assign a value to a variable right at its declaration. This is because given the initial value, Swift can infer (deduce) in most cases the type of data we intend to assign.

  1. Delete the type annotations (and the colon (:) in front of them) shown in bold:
    let numberOfVerses: Int = 4
    
    print("This song has \(numberOfVerses) verses")
    
    var numberOfTimesHeardToday: Int = 7
    numberOfTimesHeardToday = 5
    
    print("I have heard this song \(numberOfTimesHeardToday) times today")
    
    var songName: String = "Comfortably Numb"
    
    print("This song is called \(songName)")
    
    var songRating: Double = 7.5
    print("Out of 10, this song is a \(songRating)")
    
    var iAmInHere: Bool = true
    print("It is \(iAmInHere) I am in here")
    
  2. Take a look to the sidebar on the right to see that nothing has changed, and no red alerts have popped up.

  3. Swift is known as a “type-safe language.” If you try to mix multiple types on a variable, it will produce an error. For example, as shown below, add the following bold code (including commenting out the last print function) to attempt to specify a number value for songName:

    var songName = "Comfortably Numb"
    songName = 6
    // print("This song is called \(songName)")
    

    Comments are used for code that we don’t want Xcode to run. This code will now be ignored. Additionally you can use comments to explain what your code does.

  4. A red alert red alert icon will appear to the left of the line you just added. Click it.

    There’s an error because songName has already been assigned a String value, but you’re trying to add an Int value, which is not allowed.

    One common cause of iPhone app crashes is when the programmer is using one type while the app is expecting another type. Swift however, will throw an error to warn you, which is why it is known as a “type-safe language.” Type inference is letting Swift infer the type for you.

  5. Delete the songName = 6 code.

  6. Type annotation is necessary in certain circumstances. If you set a variable without declaring the initial value, Swift requires us to include the type. Delete the bold code:

    var songName = "Comfortably Numb"
    
  7. Click the red alert red alert icon that has appeared. It lets us know that the type annotation is missing.

  8. Specify it’s a String by adding the following type annotation in bold:
    var songName: String
    

    The error will disappear because you’ve specified the data type.

String Concatenation

Strings are series of characters. In this section, you’ll learn to concatenate two strings. Concatenating is putting together several strings using the + operator.

  1. First you’ll declare three new string variables. At the bottom of Xcode, type:

    var firstName: String = "James"
    var middleName: String = "Tiberius"
    var lastName: String = "Kirk"
    
  2. Now type the following bold code to create a new variable fullName:

    var fullName: String
    
    fullName = firstName + middleName + lastName
    print("\(fullName)")
    

    Here you used string interpolation to create one mutable string (a string you can mutate) by adding three variables together and creating a fourth variable from it.

  3. You may have noticed that on the right, Playground did not display any spaces between the names. To add spaces, add + " " (that’s a plus sign and a space between double quotes) between the variables:

    fullName = firstName + "  " + middleName + "  " + lastName
    

    Here, you’ve used double quotes (" ") to add spaces (which are strings) between each name variable.

  4. Notice on the right, you should now see spaces between each name.

Assignment Operators

The equals sign that you’ve been using to declare variables is an operator called the assignment operator. Below are some other compound assignment operators which can be used to perform an arithmetical operation, and an assignment in one:

Operator Use
+= Adds a value to the variable’s current value
-= Subtracts a number from the variable’s current value
/= Divides the variable’s current value by a given number
*= Multiplies the variable’s current value by a given number
  1. Let’s create a new variable using string interpolation. Add the following in bold:

    var chooseYourFavoriteName = "\(firstName) or \(middleName)"
    
  2. You can concatenate two strings using += between each string. Add the following code as shown below in bold.

    var chooseYourFavoriteName = "\(firstName) or \(middleName)"
    chooseYourFavoriteName += ". Which name do you prefer?"
    

    Let’s break this down a little more. We are essentially assigning a new value to the variable chooseYourFavoriteName. But rather than replace the existing string value, we want to tack the new string onto the end. The += is the shorthand way of saying:

    chooseYourFavoriteName = chooseYourFavoriteName + ". Which name do you prefer?"
    
  3. On the right, you should see: James or Tiberius. Which name do you prefer?

Declaring Multiple Variables In One Line Of Code

Inline multiple declaration allows us to declare more than one variable in the same line.

  1. So far, we’ve seen that we can declare three new variables such as in the example below (no need to type this out):

    var product = "lightning cable"
    var inventory = 350
    var price = 20.00
    

    Instead, we can declare more than one variable by separating them with commas.

  2. Type the following:

    var price = 20.00, inventory: Int, product = "lightning cable"
    

    Here we’ve created three new variables within the same line: price, inventory and product.

  3. If we need to declare several variables of the same type, we can do so without repeating the type for each variable. Type the following code in bold:

    var price1, price2, price3, price4: Double
    

    Here all the prices have been declared as integers with just one Double!

  4. Save the file and keep Xcode open so that we can continue with this file in the next exercise.

How to Learn iOS & Web Development

Master iOS development, web development, coding, and more with hands-on training. iOS development involves designing apps for Apple mobile devices with tools like Xcode and SwiftUI.

Yelp Facebook LinkedIn YouTube Twitter Instagram