Menu
CoddyTech

Generic Value Containers

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

Luau generic type aliases can preserve a relationship such as Envelope<T> containing a T value. Those types are checked and erased; this envelope is still a table with shared reference identity. Changing second.value therefore also changes the value observed through first.

Swift generic structs preserve element types while retaining struct value semantics. Assigning Envelope makes an independently observable value, so replacing the copy's payload preserves blue in the original. An unconstrained generic parameter permits storage and passing values, but operations such as ordering need declared requirements.

Luau

Complete Luau console program:

main.luau

type Envelope<T> = {value: T}
local first: Envelope<string> = {value = "blue"}
local second = first
second.value = "gold"
print(first.value .. " " .. second.value)

Swift

Complete program; compile the listed files together:

Envelope.swift

import Foundation
struct Envelope<Value> { var value: Value }

main.swift

import Foundation
let first = Envelope(value: "blue")
var second = first
second.value = "gold"
print(first.value, second.value)
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 Luau Developers

Practice on your own: Swift playground