Port: Policy Grade Book
Lesson 48 of 48 in Coddy's Swift for C# Developers course.
Challenge
MediumPort the C# 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 C# struct replaces its private dictionary before each successful write so copied books remain independent. A plain struct assignment alone would shallow-copy the dictionary reference. In Swift, use the required value type and accept any conforming scoring rule.
Complete C# reference for the stated input/output contract. Port this behavior into the required Swift files:
using System;
using System.Collections.Generic;
using System.Linq;
public interface IScoreRule
{
bool Accepts(int score);
}
public sealed class PassRule : IScoreRule
{
private readonly int minimum;
public PassRule(int minimum) { this.minimum = minimum; }
public bool Accepts(int score) { return score >= minimum; }
}
public struct GradeBook
{
// A struct copy initially shares this dictionary reference. Record replaces
// it with a fresh dictionary before writing, preserving independent values.
private SortedDictionary<string, int> scores;
public bool Record(string name, int score)
{
if (score < 0 || score > 100) return false;
var next = scores == null
? new SortedDictionary<string, int>(StringComparer.Ordinal)
: new SortedDictionary<string, int>(scores, StringComparer.Ordinal);
next[name] = score;
scores = next;
return true;
}
public string Report(IScoreRule rule)
{
if (scores == null) return "";
return string.Join(" ", scores.Where(pair => rule.Accepts(pair.Value))
.Select(pair => pair.Key + ":" + pair.Value));
}
}
public static class Program
{
public static void Main()
{
string[] tokens = Console.In.ReadToEnd().Split(
(char[])null, StringSplitOptions.RemoveEmptyEntries);
var rule = new PassRule(int.Parse(tokens[0]));
var book = new GradeBook();
int accepted = 0;
for (int i = 1; i < tokens.Length; i += 2)
if (book.Record(tokens[i], int.Parse(tokens[i + 1]))) accepted += 1;
string report = book.Report(rule);
Console.WriteLine(accepted + (report.Length == 0 ? "" : " " + report));
}
}Your code goes in ScoreRule.swift, PassRule.swift, GradeBook.swift, Functions.swift. main.swift holds the supplied input/output code and cannot be edited.
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 C# Developers
1Starting Swift
Working With FilesBindings and MutationNumbers and ConversionBoolean ConditionsRecap: Fare Quote4Functions and Arrays
Functions and LabelsInout and Exclusive AccessTuples and Multiple ResultsArrays Have Value SemanticsRecap: Rising Steps2Text and Decisions
Strings and InterpolationOptionals and BindingGuard and Early ExitIf and Branch ValuesRecap: Entry RulesPractice on your own: Swift playground