Dictionaries and Missing Keys
Lesson 21 of 48 in Coddy's Swift for C# Developers course.
C# dictionary indexer reads throw when a key is absent. TryGetValue exposes absence through its Boolean result and an output parameter. Swift dictionary lookup returns an optional value; writing nil through the subscript removes the key. A defaulted Swift subscript can simplify updates, but be deliberate about whether absence and a stored default value should mean different things. This example removes an existing configuration entry and reads a missing one with a fallback. It does not count word frequencies. Neither dictionary promises the lexical report order required by some tasks; sort keys explicitly before producing such output.
C#
Complete program file: Program.cs.
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
var settings = new Dictionary<string, int> { { "zoom", 125 } };
settings.Remove("zoom");
int zoom;
Console.WriteLine(settings.TryGetValue("zoom", out zoom) ? zoom : 100);
}
}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