Port: Policy Grade Book
Lesson 48 of 48 in Coddy's Swift for Go Developers course.
Challenge
MediumPort the Go 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 Go ScoreRule interface becomes a Swift protocol. Go GradeBook.Copy() explicitly copies map entries; ordinary struct assignment alone would still share its map. The required Swift GradeBook is a struct whose copied value must evolve independently. A copied Go map value does not provide that behavior. Call the supplied rule for each score so custom policies remain supported.
Complete Go reference program. Compile these package main files together; main.go contains the sole main function. The implementation is intentionally complete for this final port.
score_rule.go
package main
type ScoreRule interface { Accepts(int) bool }
pass_rule.go
package main
type PassRule struct { Minimum int }
func (rule PassRule) Accepts(score int) bool { return score >= rule.Minimum }
grade_book.go
package main
import ("sort"; "strconv"; "strings")
type GradeBook struct { scores map[string]int }
func NewGradeBook() GradeBook { return GradeBook{scores: make(map[string]int)} }
func (book GradeBook) Copy() GradeBook {
copied := NewGradeBook()
for name, score := range book.scores { copied.scores[name] = score }
return copied
}
func (book *GradeBook) Record(name string, score int) bool {
if score < 0 || score > 100 { return false }
if book.scores == nil { book.scores = make(map[string]int) }
book.scores[name] = score
return true
}
func (book GradeBook) Report(rule ScoreRule) string {
names := make([]string, 0, len(book.scores))
for name := range book.scores { names = append(names, name) }
sort.Strings(names)
rows := make([]string, 0, len(names))
for _, name := range names {
score := book.scores[name]
if rule.Accepts(score) { rows = append(rows, name+":"+strconv.Itoa(score)) }
}
return strings.Join(rows, " ")
}
main.go
package main
import ("bufio"; "fmt"; "os")
func main() {
input := bufio.NewReader(os.Stdin)
var minimum int
if _, err := fmt.Fscan(input, &minimum); err != nil { return }
rule := PassRule{Minimum: minimum}
book := NewGradeBook()
accepted := 0
for {
var name string
var score int
if _, err := fmt.Fscan(input, &name, &score); err != nil { break }
if book.Record(name, score) { accepted++ }
}
report := book.Report(rule)
fmt.Print(accepted)
if report != "" { fmt.Print(" ", report) }
fmt.Println()
}
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 Go 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