Menu
CoddyTech

Tuples and Multiple Results

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

Go functions can return multiple separate results, while a reusable grouping can use a struct. Swift can return a tuple with labeled elements, which callers access as components or destructure. Tuple labels do not create a new nominal model type.

The source receives two results directly into locals. Swift stores the returned tuple and reads its suffix and visible labels. Both use the same small values, but Go multiple return values are not themselves an ordinary first-class tuple value that can be assigned wholesale without a suitable grouping.

Go: complete program

describe.go

package main
func describe() (string, bool) { return "csv", true }

main.go

package main
import (
    "fmt"
)

func main() {
suffix, visible := describe()
    fmt.Println(suffix, visible)
}

Swift: complete program

Functions.swift

import Foundation
func describe() -> (suffix: String, visible: Bool) {
    (suffix: "csv", visible: true)
}

main.swift

import Foundation
let info = describe()
print("\(info.suffix) \(info.visible)")

Choose a named Swift struct when the grouping needs behavior or enduring domain identity. Tuples are useful for compact local results.

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 Go Developers

Practice on your own: Swift playground