Functions and Labels
Lesson 16 of 48 in Coddy's Swift for Go Developers course.
Go and Swift support free functions, but Go ordinary calls use positional arguments and do not provide language-level default parameters. Swift separates an external argument label from the local parameter name and can supply a default value.
An underscore suppresses a Swift external label. The target line function uses a default count of three, while the source supplies count explicitly. Both functions return text and their callers print it, keeping the computation separate from output ownership.
Go: complete program
main.go
package main
import (
"fmt"
"strings"
)
func line(symbol string, count int) string { return strings.Repeat(symbol, count) }
func main() {
fmt.Println(line("*", 3))
}
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("*"))Preserve required labels when implementing a Swift interface. Correct types and parameter order alone do not guarantee the expected call syntax.
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 Go 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