Tuples and Multiple Results
Lesson 18 of 48 in Coddy's Swift for R Developers course.
R functions return one object, often a named list when several different kinds of result are needed. List elements can have different types and shapes; dollar or double-bracket access selects one element. A plain list does not enforce a declared record schema at compilation.
Swift can return a tuple value containing several components. Optional labels name its components, and destructuring can bind them to local variables. Labels improve readability without declaring a new named model type; use a struct when the value needs a lasting domain identity or richer behavior.
The named R list and labeled Swift tuple both carry a label and size. Swift knows each component's type statically. The sample uses one ASCII string, so nchar and Swift Character count agree; vector inputs and combined Unicode text need separate contract decisions.
Complete R comparison program:
describe <- function(stem) list(label = toupper(stem), size = nchar(stem))
detail <- describe("map")
cat(detail$label, detail$size, sep = " ")
cat("\n")
Complete Swift comparison program, compiled from these files:
Functions.swift
func describe(_ stem: String) -> (label: String, size: Int) {
return (stem.uppercased(), stem.count)
}main.swift
let detail = describe("map")
print(detail.label, detail.size)Challenge
EasyImplement 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") }
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Swift for R 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 Steps2Text and Decisions
Strings and InterpolationOptionals and BindingGuard and Early ExitIf and Branch ValuesRecap: Entry RulesPractice on your own: Swift playground