Dictionaries and Missing Keys
Lesson 21 of 48 in Coddy's Swift for Rust Developers course.
Rust HashMap::get returns Option<&V>, borrowing a stored value when present. Copied turns the borrowed integer into an owned integer optional before defaulting. Swift Dictionary lookup returns an Optional value, and its default subscript can supply a fallback without requiring a separate unwrap expression. Merely reading a fallback in these programs does not insert a missing entry, so the count remains one. Hash-map traversal order is not a stable sorted-output contract in either example. Use explicit insertion APIs for mutation and sort keys when a report requires deterministic ordering. Distinguish an absent key from a deliberately stored optional value when designing richer maps.
Rust
fn main() {
let ages = std::collections::HashMap::from([("Mina", 12)]);
println!("{}", ages.get("Mina").copied().unwrap_or(-1));
println!("{}", ages.get("Jo").copied().unwrap_or(99));
println!("{}", ages.len());
}
Swift
let ages = ["Mina": 12]
print(ages["Mina"] ?? -1)
print(ages["Jo", default: 99])
print(ages.count)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 Rust 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