Access Control and Invariants
Lesson 39 of 48 in Coddy's Swift for R Developers course.
R closures can keep mutable state in their enclosing environment. The setter uses <<- to find that existing binding rather than creating a new local. This is an encapsulation convention, not a security or compiler-enforced privacy boundary: R introspection can reach function environments.
Swift private restricts access to the enclosing declaration and permitted same-file extensions, while fileprivate covers a file and internal covers the module. private(set) exposes a readable property at its getter's level but restricts assignments through the setter.
Swift private(set) gives a language-checked boundary between observing and assigning a property. R's captured state and Swift's private setter can both organize an API, but they enforce different guarantees. Validate transitions before changing a wallet balance so rejected operations leave it intact.
Complete R comparison program:
make_door <- function() {
opened <- FALSE
list(is_open = function() opened, open = function() { opened <<- TRUE })
}
door <- make_door()
door$open()
cat(tolower(as.character(door$is_open())), "\n", sep = "")
Complete Swift comparison program, compiled from these files:
Door.swift
final class Door {
private(set) var isOpen = false
func open() { isOpen = true }
}main.swift
let door = Door()
door.open()
print(door.isOpen)Challenge
EasyImplement Wallet(initial:) with read-only-to-callers balance, and spend(_ amount: Int) -> Bool. Reject nonpositive or unaffordable spends without changing balance; otherwise subtract and return true. Initial balance is nonnegative. Input is initial balance 0 through 1000 followed by 0 through 30 spends -10 through 1000. Output final balance then one space then number of successful spends.
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 Wallet.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 {
let w = Wallet(initial: 17); guard !w.spend(18) && !w.spend(0) && !w.spend(-1) && w.balance == 17 else { return false }; return w.spend(7) && w.balance == 10 && w.spend(10) && w.balance == 0 && !w.spend(1)
}
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 R 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 Rules5Collection Tools
Dictionaries and Missing KeysSets and MembershipUnicode and Character IndicesClosures and TransformationsRecap: Catalog Merge8Designing Types
Inheritance and OverridesComposition Through a PolicyAccess Control and InvariantsEnums with Associated ValuesFailable InitializationRecap: Booking LedgerPractice on your own: Swift playground