Menu
CoddyTech

Port: Policy Grade Book

Lesson 48 of 48 in Coddy's Swift for Java Developers course.

challenge icon

Challenge

Medium

Port the Java reference. Implement ScoreRule requiring accepts(_ score: Int) -> Bool, and PassRule(minimum:) accepting scores at least minimum. Implement value type GradeBook() with mutating record(_ name: String, score: Int) -> Bool and report(using rule: any ScoreRule) -> String. Accept scores 0 through 100; overwrite a previous score for the same name. Reject other scores without change. Report only entries accepted by the supplied rule, sorted by name, as space-separated name:score. Custom rules and independent copies must work. Input is minimum 0 through 100 followed by 0 through 30 name/score pairs. Names are lowercase ASCII words up to 10 letters; scores -10 through 110. Output count of accepted record operations, followed by a space and report only when nonempty.

Implement the required APIs and solve(_ input: String) -> String. Return output text without a final newline; do not print in editable code. The locked driver independently checks the APIs on additional valid inputs, then prints the returned text with exactly one newline. All numeric operations stay within Int bounds.

The Java ScoreRule interface becomes a Swift protocol. Java GradeBook.copy() explicitly copies the map; assignment alone aliases the Java object. The required Swift GradeBook is a struct whose copied value must evolve independently. A final reference to the Java map does not provide that behavior. Call the supplied rule for each score so custom policies remain supported.

Complete Java 17 reference program. Compile these files together; Main.java is the only entry point. The implementation is intentionally complete for this final port.

ScoreRule.java

public interface ScoreRule {
    boolean accepts(int score);
}

PassRule.java

public final class PassRule implements ScoreRule {
    private final int minimum;
    public PassRule(int minimum) { this.minimum = minimum; }
    @Override public boolean accepts(int score) { return score >= minimum; }
}

GradeBook.java

import java.util.Map;
import java.util.TreeMap;
import java.util.StringJoiner;
public final class GradeBook {
    private final Map<String, Integer> scores;
    public GradeBook() { scores = new TreeMap<>(); }
    private GradeBook(GradeBook original) { scores = new TreeMap<>(original.scores); }
    public GradeBook copy() { return new GradeBook(this); }
    public boolean record(String name, int score) {
        if (score < 0 || score > 100) return false;
        scores.put(name, score);
        return true;
    }
    public String report(ScoreRule rule) {
        StringJoiner result = new StringJoiner(" ");
        scores.forEach((name, score) -> {
            if (rule.accepts(score)) result.add(name + ":" + score);
        });
        return result.toString();
    }
}

Main.java

import java.util.Scanner;
public final class Main {
    public static void main(String[] args) {
        GradeBook book = new GradeBook();
        int accepted = 0;
        String report;
        try (Scanner input = new Scanner(System.in)) {
            ScoreRule rule = new PassRule(input.nextInt());
            while (input.hasNext()) {
                String name = input.next();
                int score = input.nextInt();
                if (book.record(name, score)) accepted++;
            }
            report = book.report(rule);
        }
        System.out.println(accepted + (report.isEmpty() ? "" : " " + report));
    }
}

Implement the Swift APIs in ScoreRule.swift, PassRule.swift, GradeBook.swift, Functions.swift. Keep the supplied main.swift driver.

Try it yourself

import Foundation
func apiChecks(_ input: String) -> Bool {
struct ProbeRule: ScoreRule { func accepts(_ score: Int) -> Bool { score % 2 == 0 } }
var b = GradeBook(); guard b.record("a", score: 40) && b.record("b", score: 71) && !b.record("a", score: 101) else { return false }; var copy = b; _ = copy.record("a", score: 88); return b.report(using: ProbeRule()) == "a:40" && copy.report(using: ProbeRule()) == "a:88" && b.report(using: PassRule(minimum: 40)) == "a:40 b:71" && PassRule(minimum: 50).accepts(50)
}
let input = String(data: FileHandle.standardInput.readDataToEndOfFile(), encoding: .utf8)!
// BEGIN PUBLIC API PROBES
let apiOK = apiChecks(input)
// END PUBLIC API PROBES
if apiOK { print(solve(input)) } else { print("API mismatch") }

All lessons in Swift for Java Developers

Practice on your own: Swift playground