Generic Value Containers
Lesson 35 of 48 in Coddy's Swift for Python Developers course.
Python code can store different object types in the same container without runtime specialization. Type hints can express relationships for static tools, but Swift checks generic relationships as part of compilation. A generic placeholder represents one concrete type for a particular instantiation.
A Swift generic struct can store values of its element type and return that same type without erasing it. Constraints such as protocol conformance enable additional operations; an unconstrained element cannot be assumed to support arithmetic or ordering. A generic struct remains a value type, subject to the semantics of its stored components.
The example keeps the left and right values of a pair and exchanges them. The task implements a container with a different access discipline; do not assume that its element type is always an integer just because the console uses integers.
Complete Python comparison program:
from dataclasses import dataclass
from typing import Generic, TypeVar
T = TypeVar("T")
@dataclass
class Pair(Generic[T]):
left: T
right: T
pair = Pair("east", "west")
pair.left, pair.right = pair.right, pair.left
print(pair.left, pair.right)Complete Swift comparison program, compiled from these files:
Pair.swift
struct Pair<Element> {
var left: Element
var right: Element
mutating func exchange() {
let old = left
left = right
right = old
}
}main.swift
var pair = Pair(left: "east", right: "west")
pair.exchange()
print(pair.left, pair.right)Challenge
EasyImplement Stack<Element> as a value type with init(), mutating push(_:), mutating pop() -> Element?, and read-only count. Pop the newest remaining item, or nil if empty. It must work for Int and String and copies must be independent. Input has 0 through 50 integers -100 through 100; push all, then pop until empty, outputting popped integers separated by spaces.
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 Stack.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 s = Stack<String>(); s.push("a"); s.push("b"); var c = s; guard c.pop() == "b" && c.count == 1 && s.count == 2 else { return false }; return s.pop() == "b" && s.pop() == "a" && s.pop() == nil
}
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 Python 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 Steps7Failures and Abstraction
Throwing Functions and CatchResult as a Stored OutcomeProtocols and ConformanceExtensions Add BehaviorGeneric Value ContainersRecap: Validated Batch2Text and Decisions
Strings and InterpolationOptionals and BindingGuard and Early ExitIf and Branch ValuesRecap: Entry RulesPractice on your own: Swift playground