Start learning free

LESSON 99 OF 292 · CONDITIONAL STATEMENTS - CHALLENGES

Top K Brands V2 in Swift: Picking the Better Brand with if/else

Practice Read the full explanation

Two brands sell the same product. Show the one with the higher rating.

You start with:

        let brand1 = "TechPro"
        let rating1 = 4
        let brand2 = "MegaCorp"
        let rating2 = 5

        var bestBrand: String
        var bestRating: Int

Build:

1. MegaCorp (5)

Rules:

  • Use if/else to pick the winner: brand1 when rating1 > rating2, otherwise brand2.
  • The starter already declares bestBrand and bestRating: assign the winner's name and rating to them inside the branches.
  • Format the result as "1. Brand (rating)" and print it with print(...).

Pick the winner into bestBrand and bestRating first, then build the output text from them.

Swift puts any value into a string with interpolation: "\(value)".

        let brand1 = "TechPro"
        let rating1 = 4
        let brand2 = "MegaCorp"
        let rating2 = 5

        var bestBrand: String
        var bestRating: Int
        if rating1 > rating2 {
            bestBrand = brand1
            bestRating = rating1
        } else {
            bestBrand = brand2
            bestRating = rating2
        }
        print("1. \(bestBrand) (\(bestRating))")

STEP 1 OF 5
    Ctrl + Enter to check

    SWIFT · CONDITIONAL STATEMENTS - CHALLENGES

    Top K Brands V2 in Swift, explained

    Problem overview

    Two brands sell the same product, and the program shows the one with the higher rating. The starter code supplies brand1 with rating1, brand2 with rating2, and two variables declared without values: bestBrand (a String) and bestRating (an Int). The branches of an if/else fill them in, and the program prints the winner as 1. Brand (rating).

    With TechPro rated 4 and MegaCorp rated 5, MegaCorp wins:

    1. MegaCorp (5)
    

    Version 1 formatted a ranked entry for one brand. This version decides which brand gets the entry.

    Approach: decide first, format once

    The decision is a single comparison: brand 1 wins when rating1 > rating2, and brand 2 wins otherwise. Note the strict comparison. When the ratings are equal, the else runs and brand 2 is shown. Whether a tie should favour the first or the second brand is a rule of the lesson, and here it is brand 2.

    The winner's name and rating are a pair, so each branch assigns both. After the if/else, one print formats the entry from bestBrand and bestRating. The formatting code appears once and works for whichever branch ran.

    On the starter data, the program compares 4 with 5. The condition is false, so the else branch runs: bestBrand becomes "MegaCorp" and bestRating becomes 5. The if branch is skipped entirely, and the final print sees only the two variables.

    The starter declares the two variables for you, so the work in this lesson is the branching itself: which values go into them, and when. Holding the winner in variables, instead of printing straight away, keeps the choice and the formatting separate.

    Step by step

    1. Open an if that tests whether rating1 is greater than rating2, and set bestBrand to brand1 inside it.
    2. Still inside the if, set bestRating to rating1.
    3. Close the if with an else, and set bestBrand to brand2 there. Not strictly better means brand 2 wins, ties included.
    4. Inside the else, set bestRating to rating2.
    5. Print the entry with interpolation: the rank 1. , the best brand, a space and an opening parenthesis, the best rating, then a closing parenthesis.

    The solution in Swift

            let brand1 = "TechPro"
            let rating1 = 4
            let brand2 = "MegaCorp"
            let rating2 = 5
    
            var bestBrand: String
            var bestRating: Int
            if rating1 > rating2 {
                bestBrand = brand1
                bestRating = rating1
            } else {
                bestBrand = brand2
                bestRating = rating2
            }
            print("1. \(bestBrand) (\(bestRating))")
    

    The Swift details worth knowing:

    • Declared, not initialized. var bestBrand: String gives a name and a type but no value. Swift lets you read the variable only after every path through the code has assigned it. With an if and an else that both assign, that holds. Delete the else branch, and the print fails to compile with variable 'bestBrand' used before being initialized, and the same message for bestRating.
    • Braces are required. Swift needs braces around the body of every if and else, even for a single statement, and the condition needs no parentheses.
    • Conditions are Bool. rating1 > rating2 gives true or false. Swift doesn't treat numbers as conditions, so if rating1 would not compile.
    • Interpolation. "1. \(bestBrand) (\(bestRating))" inserts the string and the number into the literal. The parentheses around the second hole belong to the text, and the ones attached to the backslash belong to the interpolation.
    • var versus let. The starter declares both with var. Since each is assigned once, let with the same declaration would also be accepted, but the lesson keeps the starter's var.

    Edge cases and common mistakes

    Most mistakes in this lesson come from the pair of values: the name and the rating must always come from the same brand.

    • Equal ratings. With both brands rated 5, the comparison 5 > 5 is false, and the else picks MegaCorp. Changing the condition to >= would give ties to brand 1 instead.
    • Setting only the name. If a branch assigns bestBrand but forgets bestRating, the program does not compile, because the rating might be unset at the print.
    • Swapping the pair. Assigning bestBrand = brand1 together with bestRating = rating2 prints a brand with another brand's rating. Each branch should use one brand's two values.
    • Comparing the wrong things. The comparison is between the two ratings, not the names. Strings can be compared with > in Swift, but that orders them alphabetically.
    • Reversing the comparison. rating1 < rating2 with the branches unchanged would show the lower-rated brand. Read the condition aloud: "if brand 1's rating is greater than brand 2's, brand 1 wins".
    • Two separate if statements. One if for each brand leaves a path where neither runs, for example when the ratings are equal, so the variables might be unset and the program doesn't compile. else covers every remaining case.
    • Printing inside each branch. It works, but the format string is then written twice. Choosing first and printing once avoids that.

    Testing

    • TechPro 4 against MegaCorp 5 prints 1. MegaCorp (5).
    • TechPro 5 against MegaCorp 5 also prints 1. MegaCorp (5), since a tie goes to the second brand.
    Keep going with Swift1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free