Dictionaries and Missing Keys
Lesson 21 of 48 in Coddy's Swift for Dart Developers course.
A Dart Map lookup returns a nullable value when a key may be absent. Swift Dictionary subscripting similarly returns an optional. Both distinguish a key's presence from a stored numeric zero. Swift dictionaries have value semantics, unlike Dart maps whose assignment shares an object. Swift's defaulted subscript is useful for updates, while removeValue(forKey:) returns the old value as an optional. Do not rely on Swift dictionary iteration order for a specified output. Here a cache entry is removed and its old value is reported.
Complete Dart program. Each labelled block is a separate file.
main.dart
void main() {
final cache = {'draft': 6, 'live': 0};
print(cache.remove('draft'));
print(cache['draft'] ?? -1);
print(cache['live'] ?? -1);
}Complete Swift program. Each labelled block is a separate file.
main.swift
import Foundation
var cache = ["draft": 6, "live": 0]
print(cache.removeValue(forKey: "draft") ?? -1)
print(cache["draft"] ?? -1)
print(cache["live"] ?? -1)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 Dart 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