Dictionaries and Missing Keys
Lesson 21 of 48 in Coddy's Swift for C++ Developers course.
C++ std::map::operator[] inserts a default value for a missing key, while find observes absence without inserting and at throws for a missing entry. Swift Dictionary ordinary lookup returns an Optional, and assigning nil through its subscript removes the mapping. Choose the lookup API that matches whether reading may change state. The examples remove zoom and use a fallback of 100. std::map traverses ordered keys, while std::unordered_map and Swift Dictionary do not promise the desired sorted presentation. Preserve a meaningful distinction between absence and a stored zero rather than relying on incidental default construction.
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::map<std::string, int> settings{{"zoom", 125}};
settings.erase("zoom");
auto found = settings.find("zoom");
std::cout << (found == settings.end() ? 100 : found->second) << '\n';
}
Swift
Complete program file: main.swift.
var settings = ["zoom": 125]
settings["zoom"] = nil
print(settings["zoom"] ?? 100)Challenge
EasyImplement frequencies(_:): count exact words. Input has 0 through 50 lowercase ASCII words, each 1 through 15 letters. Output word:count entries in ascending word order separated by spaces, 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 frequencies(["oak","elm","oak"] ) == ["oak":2,"elm":1] && frequencies([]).isEmpty
}
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