Start learning free

LESSON 244 OF 292 · HELPER FUNCTIONS

Letter Grades in Swift: A Helper and a Loop

Practice Read the full explanation

Given an array of integers scores, return the letter grade of every score, in the same order as the scores.

Each score gets one letter:

  • 90 to 100: "A"
  • 80 to 89: "B"
  • 70 to 79: "C"
  • 60 to 69: "D"
  • 0 to 59: "F"

The work is split between two functions. The first one is a helper: it gets one score and returns its letter. The second one, the function that is graded, goes over the scores and collects the helper's letter for each of them.

 

Example 1:

Input: scores = [95, 82, 71]
Output: ["A", "B", "C"]
Explanation: 95 is in the A range (90 to 100), 82 is in the B range and 71 is in the C range.

Example 2:

Input: scores = [65, 40]
Output: ["D", "F"]
Explanation: 65 is between 60 and 69, so it gets a D. 40 is below 60, so it gets an F.

Example 3:

Input: scores = [100, 90, 89]
Output: ["A", "A", "B"]
Explanation: 100 and 90 are both in the A range: 90 is its lowest score. 89 is one point short of it, so it gets a B.

 

Constraints:

  • scores has at least one score.
  • Every score is an integer from 0 to 100.
  • The result has one letter per score, in the same order as scores.
STEP 1 OF 9
    Ctrl + Enter to check

    SWIFT · HELPER FUNCTIONS

    Letter Grades in Swift, explained

    Problem overview

    Given an array of integer scores from 0 to 100, letterGrades returns an array of strings with one letter per score, in the same order. The ranges are 90 to 100 for "A", 80 to 89 for "B", 70 to 79 for "C", 60 to 69 for "D" and 0 to 59 for "F".

    The work is split in two. The helper letterGrade turns one score into its letter, and letterGrades loops over the array and collects the helper's answers. For [95, 82, 71] the result is ["A", "B", "C"], and for [65, 40] it is ["D", "F"]. The scores [100, 90, 89] give ["A", "A", "B"]: 90 is the lowest A, and 89 falls just short of it.

    Approach

    The helper checks the ranges from the top. A score of at least 90 is an "A". Anything that gets past that check is below 90, so "at least 80" already means 80 to 89. Each later check can therefore test a single lower bound instead of a full range such as score >= 80 && score < 90. Because return ends the function, there is no need for else. Whatever reaches the last line is below 60, which is an "F".

    The order of the checks matters. Testing score >= 60 first would give a "D" to every passing score, including 95.

    The main method is a plain collect loop: start with an empty array, visit each score, append the helper's letter, and return the array.

    Following a score through the helper

    Take 82. The first check, 82 >= 90, is false, so the function moves on. The second, 82 >= 80, is true, and the function returns "B" without looking at the remaining checks. Take 40: all four checks are false, and the function reaches return "F". A score of 90 stops at the first check and returns "A".

    The helper has no loop and no state. It maps one number to one string, and that is why it is easy to test on its own: letterGrade(59) is "F" and letterGrade(60) is "D", so the boundary can be checked directly. The main method then needs nothing beyond the collecting pattern: it never repeats the grade ranges, so if the ranges ever changed, only the helper would change.

    Step by step

    1. Check for "A" first. If score >= 90, return "A".
    2. Then "B", "C" and "D". Each check follows the same pattern with 80, 70 and 60. By the time a check runs, the higher grades have already returned.
    3. Return "F" after the last if. It needs no condition: only scores below 60 get that far.
    4. In letterGrades, create an empty [String] array named grades, declared with var because it grows.
    5. Loop over scores. The loop variable is score, and it runs once per score.
    6. Append the helper's answer. letterGrade(score) is called by its bare name, since both methods belong to the same class.
    7. Return grades after the loop. A return inside the loop would stop after the first letter.

    The solution in Swift

    class Solution {
        func letterGrade(_ score: Int) -> String {
            if score >= 90 {
                return "A"
            }
            if score >= 80 {
                return "B"
            }
            if score >= 70 {
                return "C"
            }
            if score >= 60 {
                return "D"
            }
            return "F"
        }
    
        func letterGrades(_ scores: [Int]) -> [String] {
            var grades = [String]()
            for score in scores {
                grades.append(letterGrade(score))
            }
            return grades
        }
    }
    

    Swift details worth knowing:

    • [String]() creates an empty array of strings. Writing var grades: [String] = [] is equivalent.
    • Same name, separate variables. The helper's parameter and the loop variable are both called score. They are different variables: the call passes the loop's value into the helper's parameter.
    • Single-character strings. "A" is a String, not a Character, here, because the function's return type says String.
    • The return type guarantees a value. Swift rejects a function that can reach its end without returning, which is why the final return "F" is required.

    An alternative: switch with ranges

    Swift can also express the same helper as a switch over ranges. It must be exhaustive, so the default case plays the role of the final return "F":

    switch score {
    case 90...: return "A"
    case 80..<90: return "B"
    case 70..<80: return "C"
    case 60..<70: return "D"
    default: return "F"
    }
    

    For the scores [95, 82, 71, 65, 40, 100, 90, 89] it produces ["A", "B", "C", "D", "F", "A", "A", "B"]. Both forms give the same results. The chain of if statements is the one to learn first, because it works the same way in every language and each line can be read on its own: one lower bound, one letter.

    Edge cases and common mistakes

    • Boundary scores. 90, 80, 70 and 60 belong to the higher grade, which is why the checks use >=. With >, a 90 would become a "B".
    • Wrong check order. Starting from the lowest bound gives the wrong letter for most scores.
    • Returning inside the loop. The result would hold one letter instead of one per score.
    • Declaring grades with let. An array declared with let cannot be appended to, and the compiler reports an error.

    Testing

    • [95, 82, 71] gives ["A", "B", "C"].
    • [65, 40] gives ["D", "F"].
    • [100, 90, 89] gives ["A", "A", "B"].
    • [0, 59, 60, 79, 80, 89] gives ["F", "F", "D", "C", "B", "B"].
    Keep going with Swift1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free