Menu
CoddyTech

Stored and Computed Properties

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

GDScript properties can define getters and setters behind property access syntax. Swift computed properties similarly execute code to derive a value rather than requiring a separate stored result. A property syntax alone does not reveal whether a value is stored or calculated.

The Swift belowFreezing property recomputes from celsius each time. A stored-property observer such as didSet is a different mechanism, and no observer is needed for this getter to see current state. Caching must be implemented explicitly when desired.

Both thermometers change from above freezing to below freezing after a state update. Read-only access to the derived property does not mean its result remains constant when other properties change.

Complete GDScript comparison program:

extends SceneTree
class Thermometer:
    var celsius: int = 0
    var below_freezing: bool:
        get:
            return celsius < 0

func _init():
    var meter = Thermometer.new()
    meter.celsius = 5
    print(meter.below_freezing)
    meter.celsius = -2
    print(meter.below_freezing)
    quit()

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 GDScript Developers

Practice on your own: Swift playground