Stored and Computed Properties
Lesson 27 of 48 in Coddy's Swift for C Developers course.
C uses explicit functions to derive a value from a struct. Swift computed properties provide property syntax while executing a getter. A read-only computed property need not reserve storage for its result, and reading it can depend on current stored state.
The source getter and target property describe whether a heater is enabled. Changing the stored flag changes the next result. Swift stored-property observers and computed getters or setters are distinct mechanisms; merely writing a property access does not tell you whether data is stored or calculated.
C: complete program
heater.h
#ifndef HEATER_H
#define HEATER_H
#include <stdbool.h>
typedef struct { bool enabled; } Heater;
static const char *heater_status(const Heater *heater) { return heater->enabled ? "on" : "off"; }
#endif
main.c
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include "heater.h"
int main(void) {
Heater heater = {false};
puts(heater_status(&heater));
heater.enabled = true;
puts(heater_status(&heater));
return 0;
}
Swift: complete program
Heater.swift
import Foundation
struct Heater {
var enabled: Bool
var status: String { enabled ? "on" : "off" }
}main.swift
import Foundation
var heater = Heater(enabled: false)
print(heater.status)
heater.enabled = true
print(heater.status)A computed property is not cached unless its implementation provides caching. Read-only access does not mean the result remains constant after other state changes.
Challenge
EasyImplement 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") }
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
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 Rules3Control Flow
Switch and PatternsEnums as Finite ChoicesFor Loops and RangesWhile and Repeat LoopsRecap: Sequence Scan6Values and References
Structs and Independent CopiesStored and Computed PropertiesClasses and Shared IdentityARC and Weak ReferencesRecap: Value BasketPractice on your own: Swift playground