Menu
CoddyTech

Functions and Labels

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

Luau parameters are positional. A typed options table can give a field a name such as prefix, but the caller still supplies a table value as one argument. The field contract can be checked statically; it is different from a language-level external argument label.

Swift separates argument labels from local parameter names. mark(_ text: String, with prefix: String) omits the first label, uses with at the call site and prefix inside the function. Preserve that signature exactly: the driver calls the required labels, not an equivalent options object.

Luau

Complete Luau console program:

main.luau

local function mark(text: string, options: {prefix: string}): string
  return options.prefix .. text
end
print(mark("draft", {prefix = "!"}))

Swift

Complete program; compile the listed files together:

Functions.swift

import Foundation
func mark(_ text: String, with prefix: String) -> String { prefix + text }

main.swift

import Foundation
print(mark("draft", with: "!"))
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 Luau Developers

Practice on your own: Swift playground