Day 01
Day 01 관련
First steps in Swift
As Mark Twain once said, “the secret to getting ahead is getting started.” Well, you’re starting now, so we’re going to dive in and learn about variables, constants, and simple data types.
Today you have eight one-minute videos to watch. If you want to dive deeper into each topic there is optional further reading, but you don’t need to read that unless you want to. Regardless, once you’ve finished each topic there’s a short test to help make sure you’ve understood what was taught.
I know, I know: the temptation is strong to continue on to watch more videos and take more tests beyond those linked below, but remember: don’t rush ahead! It’s much better to do one hour a day every day than do chunks with large gaps between.
1. Variables
1. Variables
When you launch Xcode it will ask you what you want to do, and I’d like you to choose “Get Started with a Playground” – this is a sandbox where you can type Swift code and see immediate results.
The default is a blank playground for iOS, which is fine, so click Next then Create to save it on your desktop.
In this video I want to introduce you to variables, which are places where you can store program data. They are called variables because they can vary – you can change their values freely.
Playgrounds start with a line of code that creates a variable for us:
var str = "Hello, playground"
That creates a new variable called str
, giving it the value “Hello, playground”. On the right of the playground you can see “Hello, playground” in the output area – that’s Xcode showing us the value was set.
Because str
is a variable we can change it:
str = "Goodbye"
We don’t need var
the second time because the variable has already been created – we’re just changing it.
1. Variable - Additional
- Optional: Why does Swift have variables?
- Test: Variables
2. Strings and integers
2. Strings and integers
Swift is what’s known as a type-safe language, which means that every variable must be of one specific type. The str
variable that Xcode created for us holds a string of letters that spell “Hello, playground”, so Swift assigns it the type String
.
On the other hand, if we want to store someone’s age we might make a variable like this:
var age = 38
That holds a whole number, so Swift assigns the type Int
– short for “integer”.
If you have large numbers, Swift lets you use underscores as thousands separators – they don’t change the number, but they do make it easier to read. For example:
var population = 8_000_000 Strings and integers are different types, and they can’t be mixed. So, while it’s safe to change str
to “Goodbye”, I can’t make it 38 because that’s an Int
not a String
.
2. Strings and integers - Additional
- Optional: Why is Swift a type-safe language?
- Test: Strings and integers
3. Multi-line strings
3. Multi-line strings
Standard Swift strings use double quotes, but you can’t include line breaks in there.
If you want multi-line strings you need slightly different syntax: start and end with three double quote marks, like this:
var str1 = """
This goes
over multiple
lines
"""
Swift is very particular about how you write those quote marks: the opening and closing triple must be on their own line, but opening and closing line breaks won’t be included in your final string.
If you only want multi-line strings to format your code neatly, and you don’t want those line breaks to actually be in your string, end each line with a \
, like this:
var str2 = """
This goes \
over multiple \
lines
"""
3. Multi-line strings - Additional
- Optional: Why does Swift need multi-line strings?
- Test: Multi-line strings
4. Doubles and Booleans
4. Doubles and Booleans
Two other basic types of data in Swift are doubles and booleans, and you’ll be using them a lot.
“Double” is short for “double-precision floating-point number”, and it’s a fancy way of saying it holds fractional values such as 38.1, or 3.141592654.
Whenever you create a variable with a fractional number, Swift automatically gives that variable the type Double
. For example:
var pi = 3.141
Doubles are different from integers, and you can’t mix them by accident.
As for booleans, they are much simpler: they just hold either true or false, and Swift will automatically assign the boolean type to any variable assigned either true or false as its value.
For example:
var awesome = true
4. Doubles and Booleans - Additional
5. String interpolation
5. String interpolation
You’ve seen how you can type values for strings directly into your code, but Swift also has a feature called string interpolation – the ability to place variables inside your strings to make them more useful.
You can place any type of variable inside your string – all you have to do is write a backslash, \,
followed by your variable name in parentheses. For example:
var score = 85
var str = "Your score was \(score)"
As you can see in the playground output, that sets the str
variable to be “Your score was 85”.
You can do this as many times as you need, making strings out of strings if you want:
var results = "The test results are here: \(str)"
As you’ll see later on, string interpolation isn’t just limited to placing variables – you can actually run code inside there.
5. String interpolation - Additional
- Optional: Why does Swift have string interpolation?
- Test: String interpolation
6. Constants
6. Constants
I already said that variables have that name because their values can change over time, and that is often useful. However, very often you want to set a value once and never change it, and so we have an alternative to the var
keyword called let
.
The let
keyword creates constants, which are values that can be set once and never again. For example:
let taylor = "swift"
If you try to change that, Xcode will refuse to run your code. It’s a form of safety: when you use constants you can no longer change something by accident.
When you write your own Swift code, you should always use let
unless you specifically want to change a value. In fact, Xcode will warn you if you use var
then don’t change the variable.
6. Constants - Additional
- Optional: Why does Swift have constants as well as variables?
- Test: Constants
7. Type annotations
7. Type annotations
Swift assigns each variable and constant a type based on what value it’s given when it’s created. So, when you write code like this Swift can see it holds a string:
let str = "Hello, playground"
That will make str
a string, so you can’t try to assign it an integer or a boolean later on. This is called type inference: Swift is able to infer the type of something based on how you created it.
If you want you can be explicit about the type of your data rather than relying on Swift’s type inference, like this:
let album: String = "Reputation"
let year: Int = 1989
let height: Double = 1.78
let taylorRocks: Bool = true
Notice that booleans have the short type name Bool
, in the same way that integers have the short type name Int
.
7. Type annotations - Additional
- Optional: Why does Swift have type annotations?
- Test: Type annotations
8. Simple types: Summary
8. Simple types: Summary
You’ve made it to the end of the first part of this series, so let’s summarize.
- You make variables using
var
and constants usinglet
. It’s preferable to use constants as often as possible. - Strings start and end with double quotes, but if you want them to run across multiple lines you should use three sets of double quotes.
- Integers hold whole numbers, doubles hold fractional numbers, and booleans hold true or false.
- String interpolation allows you to create strings from other variables and constants, placing their values inside your string.
- Swift uses type inference to assign each variable or constant a type, but you can provide explicit types if you want.
8. Simple types: Summary - Additional
- Test: Simple types
When you’re finished, don’t forget to tell other people about your progress. Yes, this is only day one, but the more motivation you get now the more you’ll be able to power through when things get tougher!
Reminder: I have a free iOS app that helps you practice Swift right on your iPhone and iPad. It contains the same lessons and tests as above, plus lots more bonus activities. And did I mention it was free? Download it here.
Tips
You can download Xcode from the Mac App Store by clicking here. As you progress in these early days you’ll build up lots of code from each day. You can keep it in different playgrounds if you want, or you can delete it – it’s down to you.