Menu
CoddyTech

Functions and Labels

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

JavaScript functions receive positional arguments, and an options object can supply named data by convention. That object is still one argument, not a language-level external argument label. Swift distinguishes the label at the call site from the parameter name inside the function.

In mark(_ text: String, with prefix: String), the first label is suppressed and the caller uses with for the second value, while the body uses prefix. Both examples return marked text and let the caller print it. Swift signatures check parameter and result types rather than relying on successful runtime property access.

JavaScript

Complete JavaScript console program:

main.js

function mark(text, options) { return options.prefix + text; }
console.log(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 JavaScript Developers

Practice on your own: Swift playground