Recap - Temperature Log
Part of the Object Oriented Programming section of Coddy's Swift journey. Lesson 16 of 57.
Challenge
HardBuild a small temperature log. Complete the enum Scale (celsius, fahrenheit, with raw values C and F) and the struct Reading, which stores the temperature in celsius. Reading has a static factory parse(_:) that reads text like 20C or 68F (returning nil for anything else), a computed property fahrenheit, and a computed label that returns 20.0C / 68.0F. The class TemperatureLog keeps an array of readings and a highest property with a didSet observer that records every new record as new high 25.0C.
The supplied code adds every parsed reading to the log (or prints bad reading: x), prints each reading's label, and finally prints the records the observer collected, one per line.
Your code goes in Scale.swift, Reading.swift and TemperatureLog.swift. main.swift holds the supplied input/output code and cannot be edited.
Try it yourself
// Supplied input/output code: keep it as it is
var input: [String] = []
while let line = readLine() { input.append(line) }
let log = TemperatureLog()
for line in input {
if let r = Reading.parse(line) {
log.add(r)
print(r.label)
} else {
print("bad reading: \(line)")
}
}
for record in log.records { print(record) }
All lessons in Object Oriented Programming
1Classes and Objects
Working With FilesDefining ClassesMethods and selfInitializersClasses Are ReferencesRecap - Library Card4Encapsulation
Access ControlRead-Only From OutsideGuarding StateFailable InitializersRecap - Bank Account7Polymorphism and Generics
PolymorphismType CastingGeneric FunctionsGeneric TypesRecap - Shape Calculator5Inheritance
SubclassesOverriding MethodsInitializers and superfinal and HierarchiesRecap - Employee Hierarchy11Project: Library Management
Books and MembersBorrowing Books3Properties in Depth
Computed PropertiesProperty ObserversStatic MembersEnums with MethodsRecap - Temperature LogPractice on your own: Swift playground