Menu
CoddyTech

Functions and Labels

Lesson 16 of 48 in Coddy's Swift for Rust Developers course.

Rust function arguments are positional. Parameter names help readers of the declaration but do not become call-site labels. Swift distinguishes an external argument label from the local parameter name, and _ suppresses the first label. The target calls greet("Mina", from: "Jo") while the function uses sender internally. Rust borrows the two strings and constructs an owned String result; Swift String values follow its value semantics without explicit borrow lifetimes in this signature. Preserve the exact target API labels because the task driver calls that declaration, not an equivalent positional wrapper with different syntax.

Rust

fn greet(person: &str, sender: &str) -> String { format!("{} greets {}", sender, person) }

fn main() {
    println!("{}", greet("Mina", "Jo"));
}

Swift

func greet(_ person: String, from sender: String) -> String {
    return "\(sender) greets \(person)"
}
print(greet("Mina", from: "Jo"))
challenge icon

Challenge

Easy

Implement perimeter(width:height:) for a rectangle. Input is width and height, each 1 through 1000. Output twice their sum. Preserve the external argument labels.

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 {
return perimeter(width: 9, height: 4) == 26 && perimeter(width: 1, height: 7) == 16
}
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 Rust Developers

Practice on your own: Swift playground