Functions and Labels
Lesson 16 of 48 in Coddy's Swift for Dart Developers course.
Dart named parameters are declared inside braces and may be optional with defaults or marked required. Swift argument labels are separate from parameter names: to person exposes to at the call while the function uses person. A default value lets callers omit that argument, but labels alone do not mean optionality. Use _ as an external label to make an argument positional. Swift calls retain parameter order even when labels are present; do not treat them as Dart's reorderable named arguments. Return types appear after an arrow in Swift.
Complete Dart program. Each labelled block is a separate file.
Functions.dart
String announce(String person, {String tone = 'hello'}) {
return '$tone $person';
}main.dart
import 'Functions.dart';
void main() {
print(announce('Ada'));
print(announce('Bo', tone: 'welcome'));
}Complete Swift program. Each labelled block is a separate file.
Functions.swift
import Foundation
func announce(to person: String, tone: String = "hello") -> String {
return tone + " " + person
}main.swift
import Foundation
print(announce(to: "Ada"))
print(announce(to: "Bo", tone: "welcome"))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 Dart 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