Learn Swift Programming: The essential step to creating iOS apps

The first step to making iOS apps is learning Swift.

But learning a new programming language can be daunting if you approach it for the first time.

Nonetheless, if you follow the right path, learning Swift can be fun and rewarding. Many developers worldwide use Swift because they like to build well-crafted programs.

In this article, I show you the right path to learning Swift.

I won’t only cover the how, but I will also explain why each piece is essential to build the whole puzzle.

Architecting SwiftUI apps with MVC and MVVM

GET THE FREE BOOK NOW

Table of contents

Chapter 1

Approaching Swift for the first time

What is Swift, and why should you learn it?

Swift is a programming language created by Apple. Most people learn Swift to make iOS apps, but Swift is used on all Apple platforms: macOS, iPadOS, watchOS, and tvOS.

While Swift is mainly used to make apps for Apple platforms, it’s also available on other operating systems, like Windows and Linux, and you can also use it to develop server-side applications.

So, if you want to make any of these things, you should learn Swift.

Some beginners wonder whether they should learn Swift or SwiftUI. The answer is yes.

Jokes aside, SwiftUI is a framework that allows you to build user interfaces for your apps. As the name suggests, it’s based on the Swift language, which you should learn first.

Is Swift difficult to learn?

The answer to this question depends on your proficiency with programming.

Learning Swift as a beginner with no programming experience

Most people who ask this question have no prior programming knowledge. That’s ok. Swift is not easier or harder to learn than other programming languages.

Ultimately, how difficult it is to learn to program depends on each individual and their skills and experience. I found programming easy to learn, but while studying computer science at university, I saw many people struggle. It’s hard to say whether that was the fault of the student, the teachers, or the approach.

So, if you’re interested in learning Swift, approach it with an open mind. Be prepared for a challenge and embrace it. Don’t be put off if you don’t get something straight away. And check in on your progress regularly to see how far you’ve come!

Learning Swift when you know programming already

Switching to Swift will be pretty easy if you already know how to program in another language. Swift is part of the C family of programming languages, so chances are that you are already familiar with most of its syntax.

And while Swift incorporates some functional programming concepts, it’s used chiefly imperatively. Many of the ideas you will find in Swift are borrowed from other programming languages. For example, protocol-oriented programming is an instantiation of mixins that you also find in other languages.

How long does it take to learn Swift?

This question is even harder to answer.

If you already know programming in another imperative language, you can become proficient in Swift in a week. However, it will take longer to understand its nuances, advanced techniques, and language constructs.

The chances are, though, that you are a beginner and don’t know how to program yet.

You will find different timelines online, ranging from weeks to months. It’s impossible to give you an estimate. It will significantly depend on how much time and effort you put into it and how effective the material you follow is.

To be clear, I am only talking about learning fundamental programming concepts to become productive and make apps. If you wish to learn about advanced language features, that will take far longer.

The good news is that you don’t have to worry about those for now. Advanced concepts are only relevant when you want to solve specific problems that only arise when you have some proficiency in programming and some experience making apps.

What is the best way to learn Swift?

As with many things in life, practice is the best teacher, and it’s crucial when learning how to program.

In theory, you can go through the basic language features in a couple of weeks. You can take a book on Swift, read it cover to cover, and what you read might even make sense to you.

But that does not mean that you will learn to program.

Programming is the act of solving problems, and you can only train that skill by solving problems. Of course, you cannot do that alone, and you will need a guide. But on the other hand, having a simple overview of all the tools at your disposal won’t teach you how to use those tools.

Some websites will teach Swift in “60 seconds” or “100 days”. My experience with my students is that those sites only give you a superficial impression of learning.

And sure, some aspects of making apps, like making a simple user interface, are indeed easy to grasp and apply. But an app’s functionality comes from its underlying code. That’s where you need to be a programmer.

Chapter 2

Grasping the basic concepts of programming

Getting the necessary software to write and run your Swift programs

The first thing you need to learn Swift programming is the right software.

The best option is to use Xcode, which is an Integrated Development Environment (IDE) that you will also use to make apps for iOS or other Apple platforms.

The easiest way to get Xcode is through the Mac App Store, but there are better ways.

Further reading: The Best and Fastest Ways to Install Xcode on your Mac

Another option you have is to use the Swift Playgrounds app. Not only does it allow you to run your code, but it also has lessons that will teach you Swift programming and iOS app development.

I would personally use Xcode, which you will need to learn to use sooner or later, but Swift Playgrounds is a much lighter app, and it can run on an iPad as well.

And if you don’t have a Mac and can’t afford a second-hand computer, you can learn Swift using Visual Studio code on Windows or Linux.

Hello, World! The first step in every programming language

The first example program you write in any language is “Hello, World!”

// This is a comment, ignored by the compiler

print("Hello World!") // You can also write a comment next to an instruction

/* This is also a comment,
which spans multiple lines
and ends only with a
closing delimiter */

This is an elementary program with one instruction that teaches you how to print something. It also teaches you how to write comments in your code that the compiler ignores.

Many think this is a useless exercise, and I thought the same at the beginning. But it teaches two fundamental concepts that you will use throughout your career. Why?

  • The print function is often the first tool many developers use to debug a program that does not work as expected, even though Xcode offers some powerful debugging tools.
  • Comments are an essential part of programming. While code should always be self-explanatory, you can use comments to note something that is not evident, like the reasons behind a piece of code. Comments are also used to create documentation.

Further reading: Hello, World! Your First Swift Program

Performing arithmetical calculations

Any program you write will manipulate values in one way or another to achieve a specific result.

The most common values you will use in Swift are numbers. At its most basic, you can use Swift to perform simple arithmetical calculations.

Swift has five arithmetical operators: addition, subtraction, multiplication, division, and remainder (or modulo).

2 + 3 // 5
7 - 4 // 3
3 * 5 // 15
9 / 3 // 3
8 % 3 // 2

When I learned programming, I thought these were irrelevant. Who cares about arithmetic? I want to make apps.

In reality, arithmetical calculations and, sometimes, more complex mathematics will be in every app you make.

  • Want to make a budget app? That’s full of arithmetic.
  • Want to make some custom control or show a cool animation? You’ll need arithmetic for the coordinates of objects.
  • Want to make a game? Games are full of stats that require arithmetic: scores, character levels, speed of things, etc.

You can’t run away from maths.

Naming values using constants and accumulating results in variables

No part of your program will be as simple and short as the examples you often find online. As a program grows, it becomes harder to track what values mean.

A fundamental part of programming is naming things. You can declare constants using the let keyword and assign a value to it using the assignment operator =.

let apples = 7
let oranges = 5
let bananas = 9
let itemCount = apples + oranges + bananas // 21

As the name implies, the value of a constant remains the same once it is assigned. If you want to change a value with a name, you must use a variable instead. Variables are declared using the var keyword.

For example, at times, you won’t have all the values you need at once, but you will need to accumulate them as your program progresses, or a user interacts with your app.

let apples = 7
var  itemCount = apples
let oranges = 5
itemCount = itemCount + oranges // 12
let bananas = 9
itemCount = itemCount + bananas // 21

This pattern of altering an existing variable by adding or subtracting something to its value is so common that Swift has several compound assignment operators to achieve the same result more concisely.

let apples = 7
var  itemCount = apples
let oranges = 5
itemCount += oranges // 12
let bananas = 9
itemCount += bananas // 21

Creating and manipulating text using strings and characters

After numbers, text is the other most common type of value you will use in your programs.

In programming, text is managed using strings, i.e., sequences of characters delimited by double quotes. The "Hello, World"! you saw in the example above is a string.

Like any other value, strings can be stored in constants or variables and combined using operators.

let subject = "I"
let verb = "have"
let object = "apples and oranges"
let sentence = subject + " " + verb + " " + object
// I have apples and oranges

You will often need to insert other values inside a string to change it dynamically based on your app’s data. These values will usually be numbers or other strings.

You do so by using string interpolation.

let apples = 7
let oranges = 5
let sentence = "I have \(apples) apples and \(oranges) oranges"
// I have 7 apples and 5 oranges
Chapter 3

Controlling the flow of execution of a program

Performing arithmetic calculations and creating human-readable string messages are at the core of every Swift program. However, if programming were limited to just these operations, it would merely function as a glorified calculator.

The true power of programming lies in making decisions, branching code based on certain conditions, controlling the order of code execution, and repeating instructions.

This collection of features is commonly referred to as control flow features in programming. In Swift, control flow is primarily managed through conditional statements such as if-else statements and for loops.

Taking decisions and branching the execution flow

The if-else statement is the most fundamental and commonly used control flow feature in any programming language. It allows you to execute different code blocks based on whether a condition is true or false.

let temperature = 25
if temperature > 30 {
	print("It's hot today.")
} else if temperature < 10 {
	print("It's cold today.")
} else {
	print("It's a nice day.")
}
// Prints "It's a nice day."

In this example, the condition temperature > 30 is evaluated first:

  • If it is true, the first block of code is executed, and the rest of the statement is skipped.
  • If it is false, the condition temperature < 10 is evaluated next.
  • If that is true, the second code block is executed, and the rest of the statement is skipped.
  • If it is false, the final code block is executed as a default case.

The true and false values are called booleans. They are often obtained by evaluating boolean expressions, which consist of comparison operators such as the equal ==, less than <, and greater than > operators, as well as logical operators like the negation !, the conjunction && and disjunction || operators.

Further reading: Take Decisions in Swift with If Statements and Boolean Operators

Quickly selecting a value based on a condition

The ternary operator is a concise shorthand for writing an if-else statement that returns a value based on a condition. It is a handy tool for creating a compact conditional statement to select a value.

let grade = 85
let result = grade >= 60 ? "Pass" : "Fail"
print(result)
// Prints "Pass"

The code above is functionally equivalent to the following complete if-else statement.

let grade = 85
let result: String
if grade >= 60 {
	result = "Pass"
} else {
	result = "Fail"
}
print(result)
// Prints "Pass"

While the ternary operator can be helpful, it should be used judiciously and not excessively or with excessive nesting, as it can reduce code readability and maintainability.

Further reading: Write Shorter Conditions with the Swift Ternary Operator

Exiting early from functions in case of errors or exceptional conditions

The guard statement is an alternative to conditional statements that allows for early termination from a function or loop if a specific condition is unsatisfied.

func greet(name: String?) {
	guard let name = name else {
		print("No name provided.")
		return
	}
	print("Hello, \(name)!")
}

greet(name: "Alice")
// Prints "Hello, Alice!"
greet(name: nil)
// Prints "No name provided."

guard statements resemble inverted if-else statements, prompting the question of why they are necessary.

While it is true that you can accomplish the same outcome with an if-else statement, a guard statement clearly indicates an early exit.

guard statements also aid in maintaining a coherent flow, placing the main execution path closer to the left, handling errors and exceptions in proximity to their corresponding tests, and minimizing the need for nested if-else statements, enhancing readability and clarity.

Further reading: Using Guards in Swift to Avoid the Pyramid of Doom

Executing different blocks of code based on complex conditions

Switch statements are an alternative method for writing conditional statements that allow you to execute different code blocks based on matching a value against multiple possible patterns.

let animal = "cat"
switch animal {
	case "dog":
		print("Woof")
	case "cat":
		print("Meow")
	case "cow":
		print("Moo")
	default:
		print("Unknown animal")
}
// Prints "Meow"

While switch statements may appear to achieve similar functionality as if-else statements with multiple clauses, they offer significantly greater power and flexibility.

They can:

  • Match various patterns, including ranges, tuples, enums, and types.
  • Assign matched values to temporary constants or variables for use within the case’s body.
  • Express complex matching conditions using a where clause for each case.
  • Enhance readability and code reuse through compound cases and fallthrough statements.

Further reading: Switch Statements in Swift: Selecting Among Multiple Options

Repeating instructions and iterating over sequences of values

Besides making decisions and changing the order of execution, Swift programs often require repeating instructions.

While a loop can be repeated a definite or indefinite number of times, the most common use of a loop is to iterate over a sequence of values, such as an array, a dictionary, a range, or a string.

for loops are Swift’s most common and valuable control flow features, and they are well-suited for iterating over arrays.

let names = ["Anna", "Alex", "Brian", "Jack"]
for name in names {
	print("Hello, \(name)!")
}
// Hello, Anna!
// Hello, Alex!
// Hello, Brian!
// Hello, Jack!

for loops can also iterate over dictionaries, which are unordered collections of key-value pairs. When iterating over a dictionary, each item is returned as a tuple, and you can decompose the tuple’s members into explicitly named constants for use within the loop’s body.

let numberOfLegs = ["spider": 8, "ant": 6, "cat": 4]
for (animalName, legCount) in numberOfLegs {
	print("\(animalName)s have \(legCount) legs")
}
// spiders have 8 legs
// ants have 6 legs
// cats have 4 legs

Suppose you don’t have a collection of values but still need to repeat some instructions a definite number of times. In that case, you can use for loops to iterate over ranges of numbers using either the closed range operator ... or the half-open range operator ..<.

for index in 1...5 {
	print("\(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 25

Further reading: For loops in Swift: a Detailed List of the Most Practical Uses

Chapter 4

Further reading

This is an ongoing series of articles on Swift for beginners. The series is currently under development, so bookmark this page and check it periodically.

Here are other articles in the series:

Architecting SwiftUI apps with MVC and MVVM

It's easy to make an app by throwing some code together. But without best practices and robust architecture, you soon end up with unmanageable spaghetti code. In this guide I'll show you how to properly structure SwiftUI apps.

GET THE FREE BOOK NOW

Leave a Comment