Access Control and Invariants
Lesson 39 of 48 in Coddy's Swift for Java Developers course.
Java uses visibility modifiers and often a private field with a public getter. Swift private(set) can expose reading while restricting writes. The default Swift access level is internal, visible within the module; it is not Java package-private visibility.
The examples publish whether a latch is open and permit changing it through a named method. The Swift setter stays private to the declaration and permitted same-file extensions. A subclass in another file does not gain permission to write a superclass private setter. Match visibility to the actual API boundary.
Java: complete program
Latch.java
public class Latch {
private boolean open = true;
public boolean isOpen() { return open; }
public void close() { open = false; }
}Main.java
import java.util.*;
import java.util.function.*;
public class Main {
public static void main(String[] args) throws Exception {
Latch latch = new Latch();
latch.close();
System.out.println(latch.isOpen());
}
}Swift: complete program
Latch.swift
import Foundation
final class Latch {
private(set) var isOpen = true
func close() { isOpen = false }
}main.swift
import Foundation
let latch = Latch()
latch.close()
print(latch.isOpen)Read access is not write access. Moving a subclass to a separate file can expose an invalid assumption about a superclass private(set) property; use an allowed superclass method instead.
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 Java 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