Menu
CoddyTech

Stored and Computed Properties

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

R can expose a derived value with a function over a list. This helper computes a scalar predicate from current celsius rather than maintaining a second field. Active bindings offer another mechanism for environment-based objects, but they are not needed for this explicit value transformation.

Swift computed properties use property syntax while deriving a result from existing state. They do not add independent stored state. A getter can read stored properties each time; a writable computed property can define a setter as well. Property observers serve a different role around stored-value changes.

Both second reads reflect the changed temperature. Swift exposes the calculation as a computed property, keeping field-like syntax without separate stored state. Derive simple facts from one source of truth instead of maintaining redundant values that can drift.

Complete R comparison program:

below_freezing <- function(meter) meter$celsius < 0L
meter <- list(celsius = 5L)
cat(tolower(as.character(below_freezing(meter))), "\n", sep = "")
meter$celsius <- -2L
cat(tolower(as.character(below_freezing(meter))), "\n", sep = "")

Complete Swift comparison program, compiled from these files:

Thermometer.swift

struct Thermometer {
    var celsius: Int
    var belowFreezing: Bool { celsius < 0 }
}

main.swift

var meter = Thermometer(celsius: 5)
print(meter.belowFreezing)
meter.celsius = -2
print(meter.belowFreezing)
challenge icon

Challenge

Easy

Implement Rectangle with mutable integer width and height, memberwise initializer, and computed area: Int. Area is width times height and must reflect later mutations. Input is width, height, then replacement width, each 1 through 100. Output area before and after the replacement.

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.

Your code goes in Rectangle.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 {
var r = Rectangle(width: 6, height: 7); guard r.area == 42 else { return false }; r.height = 2; return r.area == 12
}
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") }
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Swift for R Developers

Practice on your own: Swift playground