Tuples and Multiple Results
Lesson 18 of 48 in Coddy's Swift for Kotlin Developers course.
Kotlin commonly returns a Pair or a named data class when a function needs two results. Swift tuples provide a lightweight grouping whose elements can have labels. A function can return a named tuple, and callers may read its labels or destructure it into separate bindings. A tuple is useful for a small local relationship, while a struct is usually better when the result needs its own behavior, validation, or shared identity across an API. Tuple labels document the roles of similar values but do not define a new named type. The example separates a duration into whole days and remaining hours.
Kotlin
fun duration(hours: Int): Pair<Int, Int> = Pair(hours / 24, hours % 24)
fun main() {
val (days, hours) = duration(50)
println("$days $hours")
}Swift
func duration(_ hours: Int) -> (days: Int, hours: Int) {
return (hours / 24, hours % 24)
}
let result = duration(50)
print(result.days, result.hours)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 Kotlin 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