So in the last lesson, we said that we were going to shorten these five lines of code using the Swift 1
ternary operator. 2
So the way of the ternary operator works is that we have a condition, just as we have conditions 3
in if statements, 4
we have this condition and we check to see if it's true or if it's false. If it's true, 5
then we set this value to a particular value if it's true. 6
And if it's not true, then we set it to something else. 7
So let's try and convert our five lines of code to this format. 8
So the value in this case is the cell.accessoryType and we're going to set it to equal the condition 9
which is the same as what's between our If statement and our opening bracket. 10
So whether if item.done is equal to true. And if it is true, then the cell.accessoryType is going 11
to be set to .checkmark. But otherwise, if it's not true, then the cell.accessoryType is going to 12
be set to equal .none. 13
And that's a one line expression that does exactly the same thing as all of these lines. 14
And we can make it even shorter by getting rid of this check. 15
So this line now reads set the cell's accessoryType depending on whether the item.done is true. 16
If it is true, then set it to .checkmark. 17
And if it's not true, then set it to .none. 18
So depending on how much you've used this ternary operator or how much you've seen it used, you'll 19
begin to get comfortable with this expression. 20
And admittedly, when you first see it, it looks like magic, right? 21
It just doesn't look like a real code because it's so short and it's, you know, some would argue not as 22
explicit as this. Now, because we've come such a long way, and a big shout out to everybody who's been 23
following along 24
up till now, you've amassed a lot of knowledge. And previously in my code, I've tried to make the code 25
as explicit as humanly possible even though sometimes it's very, very cumbersome. 26
Now, as we're getting into the intermediate and advanced stages, I want to make sure that you learn and 27
you can understand some of these ways that programmers will express their code to cut down on the number 28
of lines and make that code look more succinct and more elegant. 29
So when you come across something like this in the future, you'll no longer be confused as to what it 30
means. 31
So, now I can safely delete all of that. 32
And if we run our app, let's see if despite deleting something like 10 lines of code, whether if our app 33
still works exactly the same, 34
let's just confirm. 35
So I can safely confirm that our app works exactly the same as before. 36
Even though we're making everything super short and super succinct, it's still behaving exactly as we 37
wanted to.