Generic Value Containers
Lesson 35 of 48 in Coddy's Swift for C Developers course.
C can write a concrete container, use macros to generate variants, or erase types through void pointers, each with different guarantees. Swift generics preserve static element types and can abstract over value and reference types. The C comparison deliberately uses a concrete StringPair rather than pretending a void pointer is equivalent to a checked generic.
The programs keep two choices and select the first. Swift infers String for Pair<Element> from its arguments, while the C struct explicitly stores two pointers to static text. Add protocol constraints to a Swift generic only when its operations need those capabilities.
C: complete program
pair.h
#ifndef PAIR_H
#define PAIR_H
typedef struct { const char *first; const char *second; } StringPair;
#endif
main.c
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include "pair.h"
int main(void) {
StringPair choices = {"east", "west"};
puts(choices.first);
return 0;
}
Swift: complete program
Pair.swift
import Foundation
struct Pair<Element> {
let first: Element
let second: Element
}main.swift
import Foundation
let choices = Pair(first: "east", second: "west")
print(choices.first)C pointer lifetime and conversion responsibilities do not disappear inside a container. A Swift generic declaration can preserve the actual element type without caller casts.
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 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 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