Dictionaries and Missing Keys
Lesson 21 of 48 in Coddy's Swift for C Developers course.
Standard C has no built-in dictionary container; this small comparison uses an array of entries and a lookup function with an explicit fallback. Swift Dictionary provides key lookup returning an Optional. A valid zero value must remain distinct from a missing key when the API needs that information.
The source changes a known entry and reads a missing key through the fallback. Swift keys conform to Hashable, and assigning nil through an ordinary dictionary subscript removes a mapping. Neither a custom C lookup nor Swift Dictionary should be assumed to provide sorted reports without a stated ordering rule.
C: complete program
main.c
#include <stdio.h>
#include <string.h>
typedef struct { const char *key; int value; } Entry;
static int lookup(const Entry *entries, int count, const char *key, int fallback) {
for (int i = 0; i < count; ++i) if (strcmp(entries[i].key, key) == 0) return entries[i].value;
return fallback;
}
int main(void) {
Entry settings[] = {{"zoom", 2}};
settings[0].value = 3;
printf("%d %d\n", lookup(settings, 1, "zoom", 1), lookup(settings, 1, "speed", 1));
return 0;
}
Swift: complete program
main.swift
import Foundation
var settings = ["zoom": 2]
settings["zoom"] = 3
print("\(settings["zoom"] ?? 1) \(settings["speed"] ?? 1)")Use optional binding or a deliberate default for Swift lookups. A forced unwrap is justified only when presence is established by the contract.
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