Swift newbie: What does this code actually do?

Hey,

I am trying to understand this section of code and just don’t get it.

var highestPair : (key: Int, value: Int) = (0,0)
for (key, value) in occurences {
highestPair = (value > highestPair.value) ? (key, value) : highestPair
}
let mode = highestPair.key

So we have the tuple, highestPair that accepts two values, both of type int. We have specified that the initial has the values of 0, 0 to start.
We also have a dictionary, called occurrences.
There’s iteration through the dictionary but I really don’t understand what the question mark means, is this an optional and what does the rest of the highlighted text actually do?

Can anyone help? Thank you!!

highestPair = (value > highestPair.value) ? (key, value) : highestPair

The question mark in this statement is nothing to do with an optional.
It’s the Swift Ternary Conditional Operator.
It’s shorthand for an if statement.

The line could be rewritten as:

if value > highestPair.value {
    highestPair = (key,value)
} else {
   highestPair = highestPair   // redundant - assigning variable to itself
}

In this case, the else block is redundant.

Personally, for readability in this case, I wouldn’t use the ternary operator, and would just use this …

if value > highestPair.value {
    highestPair = (key,value)
}

More info (search for Ternary): Basic Operators — The Swift Programming Language (Swift 5.7)

2 Likes

BJ (the author of that code) is a great guy! I’m glad you’re finding it useful.

You may not be ready for this, and he may introduce this later in the book, but I think that the simplest way to get that mode is

let mode = occurences.max{$0.value < $1.value}?.key

Check out Apple’s documentation on max for more info.

1 Like

Thanks, that actually makes sense now.

Thanks, I think it will be a little while before I am ready for that.

When BJ Miller’s book starts to introduce closures, the learning curve is slightly steeper…I think I will try swift apprentice first and come back to the former.

Can you actually print the PDF for the swift apprentice do you know by the way?