Extensions Add Behavior
Lesson 34 of 48 in Coddy's Swift for C++ Developers course.
C++ normally adds nonmember helper functions for built-in or existing library types; a class cannot simply be reopened to add new stored members or methods. Swift extensions can add methods, computed properties and protocol conformances to existing types without subclassing. They cannot add stored instance properties or override existing methods. The source calls a helper with an int, while Swift attaches signLabel to Int. C++ argument-dependent lookup and overloaded operators offer other customization techniques with their own rules, not the same member lookup mechanism. Choose an attached API when it expresses the operation clearly.
C++
Complete program file: main.cpp.
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <optional>
#include <memory>
#include <tuple>
#include <variant>
#include <stdexcept>
#include <algorithm>
std::string sign_label(int value) { return value < 0 ? "negative" : "nonnegative"; }
int main() {
std::cout << sign_label(-4) << '\n' << sign_label(0) << '\n';
}
Swift
Complete program file: Int.swift.
extension Int { var signLabel: String { self < 0 ? "negative" : "nonnegative" } }Complete program file: main.swift.
print((-4).signLabel)
print(0.signLabel)Challenge
EasyAdd computed String.asciiVowels: Int in a String extension in String.swift. Count ASCII vowels in either case, with duplicates. Input is a line of 0 through 80 ASCII letters and spaces. Output the count. Nonvowels contribute zero.
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 String.swift, 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 "Orange".asciiVowels == 3 && "AEe".asciiVowels == 3 && "xyz".asciiVowels == 0
}
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 Steps7Failures and Abstraction
Throwing Functions and CatchResult as a Stored OutcomeProtocols and ConformanceExtensions Add BehaviorGeneric Value ContainersRecap: Validated Batch2Text and Decisions
Strings and InterpolationOptionals and BindingGuard and Early ExitIf and Branch ValuesRecap: Entry RulesPractice on your own: Swift playground