Menu
CoddyTech

Generic Value Containers

Lesson 35 of 48 in Coddy's Swift for Dart Developers course.

Dart and Swift generics describe families of types while preserving element information. Swift constraints state required protocols rather than relying on methods that happen to exist. A generic container does not by itself clone its elements: a Swift struct containing a class reference copies that reference when assigned. Dart generic classes remain reference types. Choose a value container when replacing one whole value should be independent. The example stores a pair and returns the opposite ordering as a new pair; it does not implement a last-in-first-out collection.

Complete Dart program. Each labelled block is a separate file.

Pair.dart

class Pair<T> {
  final T first;
  final T second;
  Pair(this.first, this.second);
  Pair<T> flipped() => Pair(second, first);
}

main.dart

import 'Pair.dart';
void main() {
  final pair = Pair('north', 'south').flipped();
  print('${pair.first}/${pair.second}');
}

Complete Swift program. Each labelled block is a separate file.

Pair.swift

import Foundation
struct Pair<Element> {
    let first: Element
    let second: Element
    func flipped() -> Pair<Element> { Pair(first: second, second: first) }
}

main.swift

import Foundation
let pair = Pair(first: "north", second: "south").flipped()
print(pair.first + "/" + pair.second)
challenge icon

Challenge

Easy

Implement 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") }
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Swift for Dart Developers

Practice on your own: Swift playground