Functions and Labels
Lesson 16 of 48 in Coddy's Swift for C# Developers course.
C# callers may use named arguments, but most ordinary calls can omit those names. Swift external argument labels are part of the calling convention and usually must appear. An underscore suppresses an external label while retaining a useful parameter name inside the function. Parameters are constants within a Swift function unless you create a mutable local copy; use inout only when caller mutation is intentional. The example repeats text with a separator. Its text-building operation differs from calculating a geometric perimeter. A return type after -> describes the produced value; it does not print that value.
C#
Complete program file: Program.cs.
using System;
using System.Collections.Generic;
using System.Linq;
static class TextTools { public static string Repeat(string text, int times) { return string.Join("/", Enumerable.Repeat(text, times)); } }
class Program
{
static void Main()
{
Console.WriteLine(TextTools.Repeat("ha", times: 3));
}
}Swift
Complete program file: Functions.swift.
func repeatText(_ text: String, times: Int) -> String {
return Array(repeating: text, count: times).joined(separator: "/")
}Complete program file: main.swift.
print(repeatText("ha", times: 3))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 C# 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