Stored and Computed Properties
Lesson 27 of 48 in Coddy's Swift for C# Developers course.
C# properties and Swift computed properties both present field-like access while running accessors. A computed property does not store an independent value. Its getter derives a result from other state; a setter can translate an assigned result back into stored state. Swift uses newValue for an unnamed setter parameter. C# auto-properties create backing storage, whereas a Swift stored property is declared directly. This example converts a duration between seconds and minutes, with exact whole-minute inputs. The exercise instead derives a rectangle area. Keep initialization valid for the stored representation and document when a setter rounds or rejects a value.
C#
Complete program file: Program.cs.
using System;
using System.Collections.Generic;
using System.Linq;
class Duration { public int Seconds { get; set; } public int Minutes { get { return Seconds / 60; } set { Seconds = value * 60; } } }
class Program
{
static void Main()
{
var duration = new Duration { Seconds = 120 };
duration.Minutes = 3;
Console.WriteLine(duration.Seconds);
Console.WriteLine(duration.Minutes);
}
}Swift
Complete program file: Duration.swift.
struct Duration {
var seconds: Int
var minutes: Int {
get { seconds / 60 }
set { seconds = newValue * 60 }
}
}Complete program file: main.swift.
var duration = Duration(seconds: 120)
duration.minutes = 3
print(duration.seconds)
print(duration.minutes)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