Menu
CoddyTech

Functions and Labels

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

R calls can match arguments by name or position, with partial matching rules in some signatures. Arguments are normally lazy promises evaluated when needed. Explicit full names make a public call clearer; a Swift argument label is checked at compilation and does not implement R's lazy evaluation model.

Swift distinguishes argument labels used by callers from parameter names used inside the function. An underscore omits a label. The signature here accepts echo("ha", times: 3), but uses count inside its body. Static checking verifies the required call shape and value types.

R uses times as a formal argument and the Swift call uses times as an external label, while Swift's local parameter is count. Preserve exact labels in the target API rather than relying on abbreviated names or argument-matching behavior from R.

Complete R comparison program:

echo_sound <- function(sound, times) strrep(sound, times)
cat(echo_sound("ha", times = 3L), "\n", sep = "")

Complete Swift comparison program, compiled from these files:

Functions.swift

func echo(_ sound: String, times count: Int) -> String {
    return String(repeating: sound, count: count)
}

main.swift

print(echo("ha", times: 3))
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 R Developers

Practice on your own: Swift playground