Menu
CoddyTech

Tuples and Multiple Results

Lesson 18 of 48 in Coddy's Swift for C++ Developers course.

C++ std::tuple groups values and structured bindings give local names to its components. Swift tuples can name elements as part of the tuple interface and return several results without a separate nominal type. Those labels improve access but do not create a class or automatically define serialization fields. The examples group oak with its letter count. The C++ structured binding here is a const reference to the existing tuple, so its lifetime depends on that tuple. Swift tuple copying follows the semantics of its members. Prefer a named struct when the result needs reusable behavior or invariants.

C++

Complete program file: main.cpp.

#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <optional>
#include <memory>
#include <tuple>
#include <variant>
#include <stdexcept>
#include <algorithm>

int main() {
auto entry = std::make_tuple(std::string("oak"), 3);
    const auto &[name, letters] = entry;
    std::cout << name << '\n' << letters << '\n';
}

Swift

Complete program file: main.swift.

let entry = (name: "oak", letters: 3)
print(entry.name)
print(entry.letters)
challenge icon

Challenge

Easy

Implement bounds(_:) returning a named tuple with minimum and maximum, or nil for an empty array. Input contains 0 through 50 integers -1000 through 1000. Output minimum then maximum separated by one space, or empty.

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 Functions.swift. main.swift holds the supplied input/output code and cannot be edited.

Try it yourself

import Foundation
func apiChecks(_ input: String) -> Bool {
guard let b = bounds([6, -4, 9]) else { return false }; return b.low == -4 && b.high == 9 && bounds([]) == 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 C++ Developers

Practice on your own: Swift playground