Learn to Code iOS Apps with Swift Tutorial 1: Welcome to Programming

Learn to Code iOS Apps with Swift Tutorial 1: Welcome to Programming
Learn to Code iOS Apps in this Swift Tutorial - for complete beginners to programming!

Learn to Code iOS Apps in this Swift Tutorial – for complete beginners to programming!

Update note: This tutorial was updated for iOS 8 and Swift by Ry Bristow. Original post by Mike Jaoudi.

Have you ever thought about how awesome it would be to make your own apps for your iPhone or iPad?

There’s never been a better time to learn than now – especially since Apple just released a brand new programming language: Swift!

This is a tutorial series for complete beginners to iOS development, that will take you from the basics (like beginning Swift programming topics, or making a command-line app) all the way to making a full iOS app with a beautiful user interface.

With iOS app development, the sky is the limit. This Swift tutorial series will provide you with the basic knowledge you’ll need to make the amazing apps you’ve dreamed of!

Note: If you are a complete beginner to programming, this tutorial is for you! If you already have some experience with programming and want something faster paced, check out this tutorial series.

Getting Started

The very first step is to download Xcode – the software program that you write your apps in. You can download it for free on the Mac App Store:

Xcode on the Mac App Store

Be sure you have the latest version of Xcode – you need Xcode 6 or later to work with Swift.

Once you have Xcode installed, open Xcode and click the button that says Get started with a playground.

Get Started with a Playground

Note: If you don’t see the “Welcome to Xcode” window, click Window\Welcome to Xcode to display it.

A playground is a simple way to experiment and play around with Swift code.

You cannot run a playground as an iPhone app, but it will be very important in helping you to understand the basics of Swift. Don’t worry, you’ll be creating your very own iPhone app soon enough!

Set the name to MyPlayground, the platform to iOS, and click Next. Save the playground wherever you wish.


Introduction to Playgrounds

You will see that the playground you created already has three lines of code:

// Playground - noun: a place where people can play
import UIKit
var str = "Hello, playground"

Let’s go through each line, one at a time.

// Playground - noun: a place where people can play

This first line, which starts with two forward slashes, is called a comment.

This line is only there for you, or any other programmers that look at your code, to see. It does not affect the way that your code functions. Think of it as “a way to write notes in your code”.

import UIKit

The second line imports UIKit, which you can think of as “a bunch of code written by the smart folks at Apple.” All you need to know about this right now is that you need it for the rest of your code to work.

var str = "Hello, playground"

The third line is the one you should focus on right now.

This line creates a variable named str that holds the value Hello, playground. On the right side of the window, you can see that Xcode is keeping track of what value this variable holds.


Try changing "Hello, playground" to "Look what I can do!", like this:

var str = "Look what I can do!"

Did you see how the right side of the window changed what it said too? Congratulations, you just did some programming!

Victory is yours!

Victory is yours!

Your Own Calculator

Now let’s see what else you can do. At the bottom of your file, try typing a basic math expression such as 2 + 2 and hit enter to go to the next line:


The playground will give you the answer to your equation over in the shaded right side of the window:


Cool, eh? You can do any other math operation too.

Challenge: Quick – try to use Playgrounds to tell me the result of 123 * 456!

Solution Inside: Solution SelectShow

Enter this line in your playground:


On the right, you will see the following answer:


You’re a math genius!

Using playground as a simple calculator is great and all, but now let’s move on and get into some more coding! Delete everything in the program except for import UIKit so you have a clean slate to work with.

import UIKit

It is extremely important that you leave that line there because the Playground will not work without it.


Next, lets play some more with some variables.

You use variables to store values. When you create a variable, you always use the following syntax:

var yourVariableName: yourType = yourInitialValue

Except you substitute the following:

  • yourVariableName: Whatever you want to name the variable, like str or age for example
  • yourType: The type of the variable, like String or Int. More on that in a moment.
  • yourInitialValue: Whatever you want to set the initial value of the variable to, like “Look what I can do!” or 18.

Let’s try an example! Add these lines to the bottom of your playground:

var str: String = "Look what I can do!"
var age: Int = 18

In the first line, you created a variable named str of type String, and set the initial value to “Look what I can do!”

In the second line, you created a variable named age of type Int, and set the initial value to 18.

You’re starting to get a good idea how how to make a variable, but you may be wondering what the difference between String and Int types is, and what other types you can use. Let’s discuss that next!


Here is a list of some of the basic data types that Swift has to offer:

  • Int – whole numbers, or integers
  • Double – decimal numbers
  • Bool – a value that can be true, or false
  • String – a “string” of letters or words

Let’s practice using these data types. Add the following lines to the bottom of your playground:

var luckyNumber: Int = 7
var costOfCandy: Double = 1.25
var hungry: Bool = true
var name: String = "Ryland"

Notice how each of the values show up on the shaded right area of the window as the playground keeps track of them. Now, try changing the value of the String name.

Add the following line to the bottom of your playground:

name = "Ry"

This line did not require the use of var or : String because the object was already created. All you did here was change the value that it was storing.

Challenge: Your turn to give it a try. At the bottom of the file, try creating a variable to represent your favorite video game.

Solution Inside: Solution SelectShow

var favoriteGame: String = "Mario Kart"
favoriteGame = "Super Smash Bros."


There are also special types of variables called constants.

Rather than declaring them with var, you use the keyword let. What this does, is it makes the immutable, or unchangeable.

Whenever possible, you should use let rather than var because it allows your code to run faster because the compiler doesn’t have to account for the possibility that the value may be changed. Any data type can be used as a constant, just as any data type can be used as a variable.

Let’s try creating some now. Add this code at the bottom of your playground file:

let life: Int = 42
let pi: Double = 3.14
let canTouchThis: Bool = false
let captain: String = "Kirk"

Now try assigning a new value to captain, such as "Hook". Type this line of code at the bottom of your playground file:

captain = "Hook"

Notice that a small red symbol with an exclamation mark comes up on the far left-hand side. This is telling you that an error has occurred in your code.

Click on the symbol, and see that the error message Cannot assign to ‘let’ value ‘captain’ pops up. This is telling you that since you initialized the variable with let, therefore making it a constant, its value cannot be changed.


Remove the line captain = "Hook" to get rid of the error.

Challenge: Make a constant named favoriteNumber of type Int, and set the value to your favorite number.

Solution Inside: Solution SelectShow

let favoriteNumber: Int = 3

Inferred Typing

Tired of typing yet? No need to fear, Swift is smarter than you might think.

There is a new feature in Swift called Inferred Typing. This means that if you provide enough information when declaring and initializing the variable, Swift can predict the data type so you don’t have to include it every time.

Not only does this save time and energy from typing, but it also makes your program less cluttered and easier to follow.

To try this, find your line that says var luckyNumber: Int = 7 and replace it with the following:

var luckyNumber = 7

Well, that's convenient!

This may not seem like that big of a deal right now, but it will save you a lot of typing in the long run!

Just remember, inferred typing only works if you provide the right amount of information. If you wanted luckyNumber to be a Double, you would have had to set it equal to 7.0 (to make it clear that it’s a decimal number, rather than 7 which is an integer).

Challenge: Go back and try to make sure all of your variables and constants use inferred typing.

Solution Inside: Solution SelectShow

import UIKit
var str = "Look what I can do!"
var age = 18
var luckyNumber = 7
var costOfCandy = 1.25
var hungry = true
var name = "Ryland"
name = "Ry"
var favoriteGame = "Mario Kart"
favoriteGame = "Super Smash Bros."
let life = 42
let pi = 3.14
let canTouchThis = false
let captain = "Kirk"
let favoriteNumber = 3

Comparison Operators

Just like Playground can do simple math operations as explained earlier, it can compare numbers and values. Some of these operators include:

  • > Greater Than
  • < Less Than
  • == Equal To
  • >= Greater Than or Equal To
  • && AND
  • || OR

You can use these operators to compare two values.

Let’s give this a try! First, add these lines to the bottom of your playground to declare some variables and initiate them with values:

let batmanCoolness = 10
var supermanCoolness = 9
var aquamanCoolness = 1

Great! Now you can use these two variables to test our comparison operators. Place the following block of code at the end of your Playground file.

batmanCoolness < aquamanCoolness
supermanCoolness >= 8
batmanCoolness == (aquamanCoolness + supermanCoolness)
batmanCoolness > aquamanCoolness && batmanCoolness == (aquamanCoolness + supermanCoolness)
batmanCoolness < supermanCoolness || aquamanCoolness < supermanCoolness

Review the results in the shaded right-hand side of the window. Playground will evaluate your statements and tell you if they are true or false.

For the AND statements (&&), both comparisons have to be true. For the OR statements (||), only one of the two comparisons has to be true. If the first one is true, the program doesn’t even bother to evaluate the second because there is no need to.

Challenge: Try adding a new variable for Spiderman called spidermanCoolness and give him a coolness value. Then try using some of the comparison operators (like >, <, ==, &&, and ||) to compare Spiderman's coolness to other superheroes. (Notice that I made batmanCoolness a constant so you can’t change it 😉 )


Solution Inside: Solution SelectShow

var spidermanCoolness = 7
(spidermanCoolness + aquamanCoolness) > supermanCoolness
spidermanCoolness == 7 && aquamanCoolness == 2

If/else statements

In if/else statements, the computer executes a certain block of code if a condition is true, and does not execute the code if the condition is false.

Let’s try this! Add this example to the bottom of your playground:

if (batmanCoolness > spidermanCoolness) {
  spidermanCoolness = spidermanCoolness - 1
else if (batmanCoolness >= spidermanCoolness) {
  spidermanCoolness = spidermanCoolness - 1
else {
  spidermanCoolness = spidermanCoolness + 1

This block of code decreases Spiderman’s coolness if Batman is cooler, but increases Spiderman’s coolness if Spiderman is cooler.

As you can tell from the Playground, Spiderman’s coolness decreases to 6 from the realization that he is not as cool as Batman. As you can see from the grey area, the program never goes through the else if statement, even though it is true. That is because the program has already found that the first if statement was true, so it doesn’t even look at the rest of the code in the if/else statements.

Challenge: Create your own control flow statements using the superheroes from the last example. Remember, none of the if or else if statements have to be true. The program will either perform the else statement if you have one, or just move on to what is next in the program.

Solution Inside: Solution SelectShow

if(supermanCoolness < spidermanCoolness)  {
  supermanCoolness = supermanCoolness - 1 
  spidermanCoolness = spidermanCoolness + 1
else if (supermanCoolness == spidermanCoolness)  {
  supermanCoolness = supermanCoolness + 1
  spidermanCoolness = spidermanCoolness + 1
else  {
  supermanCoolness = supermanCoolness + 1 
  spidermanCoolness = spidermanCoolness - 1

Simple Functions

Functions are blocks of code that perform a certain task. For example, a function named printMyFavoriteSnack() might print out "Pringles".

Editor and Podcaster Mic Pringle

You can either write and use your own functions, or use functions written by other programmers. For example, Apple has provided a bunch of built-in functions that do useful things that you can use in your apps.

One example is the println() function. When you call println, the program “prints” whatever you type inside the parentheses to the console.

Let’s try a quick example. Type the following at the bottom of your file:

println("Hello, World")

You should see “Hello, World” printed out on the right hand side.

Programming anything involves using a lot of different functions. Sometimes you use functions written by Apple or by other people, as you have just done, and sometimes you write your own, as you will experience further along.

Challenge: Try changing the string inside the println() function to say something nice about yourself. Also, try putting one of the superhero coolness factor variables in there and see what happens.

Solution Inside: Solution SelectShow

println("Ry is awesome")

String Interpolation

Printing strings to the console is great and all, but wouldn’t it be great if you could combine a string and the value from a variable in the same print statement?

Good news, everyone! You can! It’s called String Interpolation.

This is very useful when you want to say something like “Sally has (some value) apples.” Try out this code at the bottom of your playground:

var apples = 5
println("Sally has \(apples) apples")

See that? By using the format \(variable name), you can put the value of any variable you want into a String. You can even perform operations inside the parentheses if you want. Add this code to the bottom of your playground:

println("Sally has \(apples - 5) apples")

Nice job! String Interpolation is something that you will be using for just about every program that you write.


Challenge: Now it’s time to combine some of the concepts that you have learned. Create two variables for grades for students in a class: John’s grade (95), and Sam’s Grade (85). Then make an if/else statement that compares John’s and Sam’s grade, and prints out whether John’s grade is less than, greater than, or equal to Sam’s grade. You can do it!

Solution Inside: Solution SelectShow

var johnsGrade = 95
var samsGrade = 82
if (johnsGrade < samsGrade) {
  println("\(johnsGrade) is less than \(samsGrade)")
else if (johnsGrade > samsGrade) {
  println("\(johnsGrade) is greater than \(samsGrade)")
else {
  println("\(johnsGrade) is equal to \(samsGrade)")

While Loops

While loops are another kind of control flow statement, like the if/else statements you learned earlier. They are similar in the fact that they require a condition to execute.

However, instead of simply executing its code block once, while statements continue to execute the code block as long as its condition remains true. Type out this example at the bottom of your playground.

var secondsLeft = 3
while (secondsLeft > 0) {
  secondsLeft = secondsLeft - 1
println("Blast off!")

Make sure that you code some way of making sure that the condition becomes false at some point. You do not want to create an infinite loop because it will cause all kinds of problems and your program will not reach anything after the loop.

When you run this, you will see the line (3 times) on the right hand side, which represents that the println() statement is running each time. Since there are multiple values printed out, you have to bring up another window called the Assistant Editor to see them.

To do this, go to the top of your screen and select View\Assistant Editor\Show Assistant Editor. In the box marked Console Output, you should be able to see what you printed:


Challenge: Go ahead and try writing your own while loop – for example make a while loop about a cop eating a box of donuts. Remember, no infinite loops!

Solution Inside: Solution SelectShow

var donutsLeft = 6
while(donutsLeft > 0)  {
  println("You have \(donutsLeft) donuts left")
  donutsLeft = donutsLeft - 1
  println("You eat one donut")
println("You are all out of donuts :(")

Break Statement

Say you have some kind of loop in your program, like a while loop, and you want to exit the loop if a specific thing happens. That’s where the break command comes in. Follow along with this example by writing out the code at the end of your playground.

var cokesLeft = 7
var fantasLeft = 4
while(cokesLeft > 0)  {
  println("You have \(cokesLeft) Cokes left.")
  cokesLeft = cokesLeft - 1
  if(cokesLeft <= fantasLeft)  {
println("You stop drinking Cokes.")

In this example, you want to keep drinking Coke until there are none left. However, you realize that you also have Fanta in the fridge. You decide you should stop drinking Coke when you have the same amount or less than Fanta because then you would have to start drinking the Fanta to even it out. When this situation occurs, you exit the loop, and thereby stop drinking the Coke.

Challenge: Now it’s your turn to try. Create a while loop that eventually has an ending point – for example a loop about goofing off until the boss stops by. In that loop, add an if statement where you use break to exit from the loop.

Solution Inside: Solution SelectShow

var goofOffTime = 10
var bossComing = 0
while(goofOffTime > 0)  {
  println("Goofing off!")
  goofOffTime = goofOffTime - 1
  bossComing = bossComing + 1
  if(goofOffTime == bossComing)  {
println("Done goofing off.")

Continue Statement

The continue statement is very similar to the break statement, however, instead of exiting from the loop, it just sends the program back to the beginning of the loop. Type in the example below at the end of your playground.

var numbers = 0
while(numbers <= 10)  {
  if(numbers == 9)  {
    numbers = numbers + 1
  numbers = numbers + 1

As you can see from what the program printed to the console, every number from 0 to 10 was printed except 9 because of the continue statement. It’s too bad that 7 ate 9, but for that reason, you can’t include him in our list.


Challenge: Use continue in your own loop. Find a reason to have a specific value miss commands that other values have to execute and use the continue statement to go to the top of the loop.

Solution Inside: Solution SelectShow

println("List of World Wars:")
var ww = 1
while(ww <= 5)  {
  if(ww == 3 || ww == 4)  {
    ww = ww + 1
  println("World War \(ww)")
  ww = ww + 1
println("That's the beauty of World War V, Lois. It's so intense it skips over the other two. - Peter Griffin")


Sometimes, due to the use of different functions, you don’t know if a variable will have a value or not. When it does not have a value, it is said to contain nil. This is where optionals come in.

Optionals are variables that can either contain a value or contain nil. Declare an optional and notice you can set it to nil:

var optionalNumber: Int? = 5
optionalNumber = nil

The ? is what declares the value as an optional. To figure out if optionals contain a value or are set to nil, you use something called an if let statement. It looks something like this:

if let number = optionalNumber

if let statements act similar to if statements. If optionalNumber contains an Int, number is set to that value and the code inside the if let curly braces is executed.

Optionally, you can set up an else statement to execute if optionalNumber happens to be nil.

Challenge: Try this out yourself. Write an if let statement for optionalNumber to print different Strings if it contains a value or if it is nil.

Solution Inside: Solution SelectShow

if let number = optionalNumber  {
  println("It is a number")
else  {
  println("It is not a number")

Conversion Between Data Types

Let’s see how this can be useful in a program. Optionals can help you to convert between variable types. Try the example below where a String is converted into an Int.

var languagesLearned: String = "3"
var languagesLearnedNum: Int? = languagesLearned.toInt()

Here, after declaring and initializing languagesLearned as a String with the value "3", you declare the optional languagesLearnedNum and initialize it with the method toInt(). Methods are very similar to functions like println() that you learned earlier, except that they are a part of a class. You will learn more about that later.

toInt() is a method that has already been written, so all you have to know is that it takes String variables and returns their value in Int form. The reason that you have to set an optional like languagesLearnedNum equal to that value is because it has the potential to be nil. This occurs if the String you are trying to convert does not contain a numerical value, but contains something like "Hello, World".

Enter in the following code to test this out:

if let num = languagesLearnedNum  {
  println("It is a number")
else  {
  println("It is not a number")

The if let statement tests to see if languagesLearnedNum actually contains a value, or if it is nil. If it contains a value, that value is passed to num and the code inside the curly braces is executed. If not, the code inside of the else curly braces is executed.

See what happens if you change the String in languagesLearned to "Three". The program should print "It is not a number" to the console because languagesLearnedNum will be set to nil when the program tries to convert "Three" to an Int.

Putting it all together

Challenge: Last one! Try creating your own variables where you try to convert a String to an Int. Then, compare these variables to other variables you set in if statements that contain println() statements. These println() statements should contain Strings with String Interpolation so you can say which values are greater than/less than which values.

Solution Inside SelectShow

var tutorialTeam: String = "55"
var editorialTeam = 23
var tutorialTeamNum: Int? = tutorialTeam.toInt()
if let numTutorial = tutorialTeamNum  {
  if(numTutorial > editorialTeam)  {
    println("\(numTutorial) is greater than \(editorialTeam)")
  else if (numTutorial < editorialTeam) {
    println("\(numTutorial) is less than \(editorialTeam)")
  else  {
    println("\(numTutorial) is equal to \(editorialTeam)")
else  {
  println("Invalid entry")

Where To Go From Here?

Here is the finished playground file for this tutorial series so far.

Stay tuned for the next part of the series, where you’ll learn how to take your Swift knowledge and make a simple command-line number guessing game!

In the meantime, if you have any questions or comments, please join the forum discussion below!

Learn to Code iOS Apps with Swift Tutorial 1: Welcome to Programming is a post from: Ray Wenderlich

The post Learn to Code iOS Apps with Swift Tutorial 1: Welcome to Programming appeared first on Ray Wenderlich.



Write a comment