Menu
CoddyTech

Stored and Computed Properties

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

Luau can express a derived property as a function over a typed record. This empty function computes from the current text on every call instead of maintaining a separate flag. Metatable __index can provide property-like behavior, but the explicit function keeps this example's dependency visible.

Swift computed properties use property syntax while calculating from existing state. BufferState.empty reflects the changed text on its next read and introduces no stored Boolean. When one value is entirely determined by another, computing it avoids inconsistent duplicate state.

Luau

Complete Luau console program:

main.luau

local buffer = {text = ""}
local function empty(state: {text: string}): boolean
  return state.text == ""
end
print(empty(buffer))
buffer.text = "ink"
print(empty(buffer))

Swift

Complete program; compile the listed files together:

BufferState.swift

import Foundation
struct BufferState {
    var text = ""
    var empty: Bool { text.isEmpty }
}

main.swift

import Foundation
var buffer = BufferState()
print(buffer.empty)
buffer.text = "ink"
print(buffer.empty)
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 Luau Developers

Practice on your own: Swift playground