Day 3 - 100 Days of Swift

6 minute read

Operators and Conditions

Day 3 is about the various operators and ways to control the flow of logic. You look at the arithmetic operators, how those same operators are overloaded, and the compound assignment operators. You look at the conditional operators and how to combine them with && and ||. You also look at if statements, the ternary operator, switch statements and range operators. All the great operators.

You use the arithmetic operators to do math stuff:

1
2
3
4
1 + 1 // 2
6 - 3 // 3
5 * 4 // 20
9 / 3 // 3

There is even an operator to get the remainder of a division:

1
11 % 3 // 2

In Swift, some operators are overloaded, meaning they can be used with different types. So you can add two strings together, or add two arrays together:

1
2
3
"You" + " " + "Rock" // "You Rock"

[0, 1] + [2, 3]      // [0, 1, 2, 3]

The compound assignment operators allow you to perform an operation and update a variable in place:

1
2
3
4
5
6
var health = 10   // 10
health -= 2       // 8

var greeting = "Hello "
var name = "Ron"
greeting += name  // "Hello Ron"

The comparison operators return a Bool which tells you if the comparison is true or not:

1
2
3
4
4 == 9 // false
5 != 6 // true
4 > 9  // false
5 <= 6 // true

If statements let you perform a block of code if the condition is true:

1
2
3
4
5
var isHungry = true

if isHungry {
	eatSomeFood()
}

You can also give it some code to run if the condition is false, or even check multiple conditions:

1
2
3
4
5
6
7
8
9
10
11
var score = 92

if score > 98 {
	print("You passed with flying colors!")
} else if score > 89 {
	print("You did great!")
} else if score > 65 {
	print("You passed")
} else {
	print("You didn't pass. Better luck next time.")
}

You can use && (AND) or || (OR) to combine conditions:

1
2
3
4
5
6
7
if hasLittleSebastian && hasFunnelCakes {
	print("This is a great party!")
}

if jerryFarts || jerryFalls {
	print("Everyone laughs, no one is surprised.")
}

The ternary operator is a concise way to return one of two values based on a condition:

1
let ronsMood = isTammyPresent ? "Bad" : "Good"

If you have a lot of cases to check, the switch statement might be more readable than a bunch of if-else if blocks, but you have to make sure to cover all possible cases. That’s where the default case comes in handy:

1
2
3
4
5
6
7
8
switch flavor {
case chocolate:
	print("Chocolate is my favorite!")
case vanilla
	print("Seems a little bland")
default:
	print("Who cares? I just love ice cream!")
}

There are also two range operators which let you communicate a range. Either a half-open range, meaning the first operand is included and it goes up to but doesn’t include the second, or a closed range, which means it includes both operands and all the possibilities in between:

1
2
3
1..<10 // 1, 2, 3, 4, 5, 6, 7, 8, 9

1...10 // 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

These can be useful in conjunction with switch statements to cover a bunch of cases at once:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
switch year {
case 1820..<1824:
	return "The Paris of America"
case 1824..<1939:
	return "The Akron of Southwest Indiana"
case 1939..<1945:
	return "Welcome German Soldiers"
case 1945..<1964:
	return "The Factory Fire Capital of America"
case 1964..<1974:
	return "Welcome Vietnamese Soldiers"
case 1974..<1976:
	return "Engage with Zorp"
case 1976:
	return "Zorp is Dead. Long Live Zorp"
case 1977..<1985:
	return "It's Save to be Here Now!"
case 1985..<1988:
	return "Birthplace of Julia Roberts"
case 1988..<2001:
	return "Home of the World Famous Julia Roberts Lawsuit"
case 2001..<2009:
	return "Welcome Taliban Soldiers"
default:
	return "First in Friendship, Fourth in Obesity"
}

Reflections

I know. It is only day three and I’ve already skipped a day. But it was Mother’s day and I was busy. And I’m getting back on the horse today. Trying not to miss any. Day 3’s material is good. We’ve finally gotten to something that lets you do something with all the stuff we learned how to define on the first two days. You’ve got the building blocks for all kinds of math, you’ve got logical comparisons and ways to control the flow of the code. There are all sorts of interesting problems that you could solve with just the stuff we’ve learned so far (although it may be a little verbose). The only thing that really stood out to me today was how much he discouraged the use of the ternary operator. He seemed to think that it leads to less readable code. I do see how if you tried to shoe-horn every if statement into the ternary operator, things could get a little ugly, but I think there are just as many situations where it is more straightforward and readable to use the ternary operator. Especially if you are assigning a new variable, and all three operands are relatively short in length. To each his own I guess.