Day 1 - 100 Days of Swift

3 minute read

Intro

I am a little behind the curve on this one, but in order to keep myself sharp on my Swift skills, I’ve decided to work my way through Paul Hudson’s 100 days of Swift. Part of the challenge is doing it somewhat publicly and so I am committing to blog at least a little bit about each day. I’m sure what that looks like will change over time, but for now I just want to get started. Here it goes…

Day 1

The first day is, unsurprisingly, pretty basic. It covers creating variables and constants, the basic types of String, Int, Double, and Bool, string interpolation, and type annotations/inference. In summary:

You create variables like this:

1
var variable = "This value can change"

And you reassign them like this:

1
variable = "Now it is this"

You create constants like this:

1
let constant = "This one can't change"

Strings are bits of text:

1
"This is a string. The stuff between the double quotes"

Multi-line strings look like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
"""
Multi-line strings have to go between
sets of triple double quotes.
The triple quotes must be on their own line
but the first and last return don't count.
"""

"""
If the string is multi-line \
for formatting reasons \
and you don't actually want \
newlines in the string \
you can escape them with backslashes
"""

Integers are whole numbers:

1
2
3
42
2319
24601

Doubles are floating-point numbers:

1
2
3
0.125
3.14159
1.6180339887

Booleans are either true or false:

1
2
let booleansAreBinary = true
let booleansAreLame = false

You can interpolate constant or variable values (or other code) into a string by putting it into a set of parentheses with a backslash in front of it, like this:

1
2
3
4
5
6
7
var previousHighScore = 101
var highScore = 127
"Your high score is \(highScore)."
"That's \(highScore - previousHighScore) more than the old one!"
// Becomes:
// "Your high score is 127."
// "That's 26 more than the old one!"

Typically the compiler is smart enough to infer what type you want just by what it looks like, but if you want to declare a Double that looks like this: 10, you can tell the compiler what type you mean with an annotation:

1
2
3
let inferredDouble = 10.0
let inferredInt = 10
let annotatedDouble: Double = 10

Reflections

That’s pretty much all there is to the first day. It seems pretty basic to me now that I’ve spent so much time looking at Swift. But there was a time when it was new to me, just like I’m sure it is new to many of the people who start at day 1. All in all, for me it was a good review of the terms and a good way to start. One day down, ninety nine to go.