Sets and Membership
Lesson 22 of 48 in Coddy's Swift for C++ Developers course.
C++ std::set stores distinct keys in comparator order, while std::unordered_set uses hashing without sorted traversal. Swift Set requires Hashable elements and also does not promise sorted iteration. The target sorts its names explicitly, whereas this source ordered set already supplies sorted order. Removing an absent key is harmless and inserting a duplicate does not increase membership. C++ set insertion returns an iterator and an inserted flag; Swift insert returns a tuple describing insertion and the member after insertion. Both examples remove sync and retain search. Uniqueness and display order remain separate container properties.
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>
int main() {
std::set<std::string> enabled{"search", "sync", "search"};
enabled.erase("sync");
for (const auto &name : enabled) std::cout << name << '\n';
}
Swift
Complete program file: main.swift.
var enabled: Set<String> = ["search", "sync", "search"]
enabled.remove("sync")
print(enabled.sorted().joined(separator: ","))Challenge
EasyImplement overlap(_:_:): return distinct shared integers sorted ascending. Input is two lists separated by one |; each list contains 0 through 30 whitespace-separated integers -100 through 100. Output space-separated shared values or a blank line.
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 overlap([4,4,2],[2,4,4]) == [2,4] && overlap([], [1]) == []
}
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 Rules5Collection Tools
Dictionaries and Missing KeysSets and MembershipUnicode and Character IndicesClosures and TransformationsRecap: Catalog MergePractice on your own: Swift playground