Menu
CoddyTech

Functions and Labels

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

Ruby distinguishes positional and keyword parameters. Times is a required keyword here, and the method's final expression supplies its return value. A Ruby keyword name is the local parameter name, while Swift can give the caller a different external label from the parameter used inside the function.

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.

Both calls use times, but Swift names the local parameter count and suppresses the first label with an underscore. Read the required signature exactly. A correct result behind the wrong labels is a different API from the one the locked driver calls.

Complete Ruby comparison program:

def echo(sound, times:)
  sound * times
end
puts echo("ha", times: 3)

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

Practice on your own: Swift playground