Functions and Labels
Lesson 16 of 48 in Coddy's Swift for Java Developers course.
Java methods belong to classes; a static utility method needs no instance. Swift can declare free functions at module scope. In these examples free functions belong in Functions.swift, while main.swift only calls them.
Swift separates the argument label used by a caller from the parameter name used in the function body. An underscore removes an external label. A default parameter value lets a caller omit that argument, a common alternative to a Java overload.
Java: complete program
Main.java
import java.util.*;
import java.util.function.*;
public class Main {
static String line(String symbol) { return line(symbol, 3); }
static String line(String symbol, int count) { return symbol.repeat(count); }
public static void main(String[] args) throws Exception {
System.out.println(line("*"));
}
}Swift: complete program
Functions.swift
import Foundation
func line(_ symbol: String, count: Int = 3) -> String {
String(repeating: symbol, count: count)
}main.swift
import Foundation
print(line("*"))Java argument names are not part of call syntax. In Swift the required external labels are part of the callable interface, so preserving only parameter order is insufficient.
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 Java 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