Start learning free

LESSON 185 OF 292 · LOOPING OVER ARRAY INDICES

Employee of the Year V4 in Swift: Finding the Best with a Loop

Practice Read the full explanation

A whole team is competing. Use a for loop over the arrays to find the most productive employee, then print their 15% bonus.

You start with:

        let names = ["John Doe", "Mary Jane", "Bob Smith", "Alice Chen", "Carlos Diaz"]
        let productivities = [83, 133, 97, 150, 120]
        let salaries = [135000, 335000, 210000, 250000, 180000]

Build:

Alice Chen
Bonus: $37500

Rules:

  • Index i in all three arrays refers to the same employee.
  • The winner is whichever employee has the highest productivity. If two employees share the highest productivity, the one listed first wins.
  • The winner's bonus is 15% of their salary, rounded down to a whole number.
  • Print the winner's name on the first line, then "Bonus: $<amount>" on the second.

Start with var bestIndex = 0 and loop over the other indices with for i in 1..<names.count. Inside the loop, update the best index only when productivities[i] > productivities[bestIndex]: a strict comparison keeps the first employee on a tie.

Dividing two whole numbers (Int) drops the fraction, so salaries[bestIndex] * 15 / 100 is already rounded down: let bonus = salaries[bestIndex] * 15 / 100

Convert the number with String(...) (or use \(...) inside the text): print("Bonus: $" + String(bonus))

        let names = ["John Doe", "Mary Jane", "Bob Smith", "Alice Chen", "Carlos Diaz"]
        let productivities = [83, 133, 97, 150, 120]
        let salaries = [135000, 335000, 210000, 250000, 180000]

        var bestIndex = 0
        for i in 1..<names.count {
            if productivities[i] > productivities[bestIndex] {
                bestIndex = i
            }
        }
        let bonus = salaries[bestIndex] * 15 / 100
        print(names[bestIndex])
        print("Bonus: $" + String(bonus))

STEP 1 OF 6
    Ctrl + Enter to check

    SWIFT · LOOPING OVER ARRAY INDICES

    Employee Of The Year V4 in Swift, explained

    Problem overview

    A whole team competes, stored as three parallel arrays: names, productivities and salaries. Index i in all three refers to the same employee. The winner has the highest productivity, and if two employees share the highest score, the one listed first wins. The program prints the winner's name and a bonus of 15% of their salary, rounded down.

    For the starter data, the highest productivity is 150, which belongs to Alice Chen at index 3. Her salary is 250000, so the bonus is 37500:

    Alice Chen
    Bonus: $37500
    

    The earlier versions compared a fixed number of employees with if statements. A loop makes the code work for any number of them, and the rest of the program stays the same.

    Approach: keep the index of the best so far

    The idea is a running champion. Start by assuming employee 0 is the best, and keep that employee's index in bestIndex. Then visit every other employee once. Whenever one has a strictly higher productivity than the current champion, that employee becomes the new champion.

    Storing the index, not the productivity, is the key choice. One index reaches into all three arrays, so at the end names[bestIndex] and salaries[bestIndex] give the winner's name and salary together.

    The comparison is strictly greater. On a tie, the challenger is not strictly better, so the earlier employee stays in front, which is the tie rule.

    The loop on the starter data

    iproductivities[i]bestIndex after the check
    11331
    2971
    31503
    41203

    Employee 1 beats employee 0 (133 against 83), and employee 3 beats employee 1 (150 against 133). Nobody beats 150, so the loop ends with bestIndex equal to 3.

    Step by step

    1. Create bestIndex with var, starting at 0. It changes while the loop runs, so it can't be a let.
    2. Write the for loop over 1..<names.count. Employee 0 is already the champion, so there is nothing to compare at index 0, and the loop starts at 1.
    3. Inside the loop, compare productivities[i] with productivities[bestIndex]. When the first is strictly greater, set bestIndex to i.
    4. After the loop, compute bonus as salaries[bestIndex] * 15 / 100. Integer division rounds down.
    5. Print names[bestIndex] on its own line.
    6. Print the bonus line, with the number converted by String(...) before it is joined to the text.

    The solution in Swift

            let names = ["John Doe", "Mary Jane", "Bob Smith", "Alice Chen", "Carlos Diaz"]
            let productivities = [83, 133, 97, 150, 120]
            let salaries = [135000, 335000, 210000, 250000, 180000]
    
            var bestIndex = 0
            for i in 1..<names.count {
                if productivities[i] > productivities[bestIndex] {
                    bestIndex = i
                }
            }
            let bonus = salaries[bestIndex] * 15 / 100
            print(names[bestIndex])
            print("Bonus: $" + String(bonus))
    

    The Swift details worth knowing:

    • Half-open ranges. 1..<names.count includes 1 and stops before names.count. For five names, i takes the values 1, 2, 3 and 4, which are all the valid remaining indices. The closed range 1...names.count would reach index 5 and crash.
    • Arrays are inferred. The literals give [String] and [Int]. Indexing an array out of bounds stops the program with a run-time error, so each index must stay between 0 and count - 1.
    • let arrays. The three arrays are constants, which is fine because the program only reads them. Only bestIndex changes.
    • Integer arithmetic. Int is 64 bits in Swift, so these salaries are nowhere near overflow. If arithmetic did overflow, Swift would trap and crash, not wrap around silently.

    Edge cases and common mistakes

    • A tie for the top. If Mary Jane's productivity is changed to 150, both she and Alice Chen have 150. The program prints Mary Jane and Bonus: $50250, because she is listed first and Alice's 150 is not strictly greater.
    • Using >=. It would let the later employee replace the earlier one on every tie. In that same tie, Alice would win.
    • A single employee. With one name, 1..<1 is an empty range, so the loop body never runs and employee 0 wins. With the data for John Doe alone, the program prints John Doe and Bonus: $20250.
    • No employees. With empty arrays, the range 1..<0 is invalid in Swift, and names[0] would not exist either, so the program crashes. The lesson's data always has at least one employee.
    • Tracking the productivity instead of the index. Remembering only the best score tells you who is best by score but not whose name and salary to print.
    • Starting bestIndex at 0 but looping from 0. It works, because an employee compared with themselves is not strictly greater, but it does one useless comparison.

    Testing

    • The starter data prints Alice Chen and Bonus: $37500.
    • With productivities [83, 150, 97, 150, 120], the output is Mary Jane and Bonus: $50250.
    • With the single employee John Doe (productivity 83, salary 135000), the output is John Doe and Bonus: $20250.
    Keep going with Swift1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free