Functions and Labels
Lesson 16 of 48 in Coddy's Swift for Kotlin Developers course.
Swift separates an external argument label from the parameter name used inside a function. By default the parameter name is also its call-site label. An underscore suppresses that external label, and a different word gives callers a more readable phrase. Kotlin named arguments are selected at the call site; Swift labels are part of the declared function interface and normally must appear in calls. Return types follow an arrow in Swift instead of Kotlin colon syntax. Parameters are immutable local bindings unless the function makes a separate mutable copy. The example builds a greeting using different external and internal names.
Kotlin
fun greet(person: String, from: String): String = "$from greets $person"
fun main() { println(greet(person = "Mina", from = "Jo")) }Swift
func greet(_ person: String, from sender: String) -> String {
return "\(sender) greets \(person)"
}
print(greet("Mina", from: "Jo"))Challenge
EasyImplement 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") }
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Swift for Kotlin Developers
1Starting Swift
Working With FilesBindings and MutationNumbers and ConversionBoolean ConditionsRecap: Fare Quote4Functions and Arrays
Functions and LabelsInout and Exclusive AccessTuples and Multiple ResultsArrays Have Value SemanticsRecap: Rising Steps2Text and Decisions
Strings and InterpolationOptionals and BindingGuard and Early ExitIf and Branch ValuesRecap: Entry RulesPractice on your own: Swift playground