Dictionaries and Missing Keys
Lesson 21 of 48 in Coddy's Swift for Go Developers course.
Go map lookup returns the element zero value for a missing key, with the optional comma-ok result distinguishing absence from a stored zero. Swift Dictionary packages that distinction into an Optional result. A fallback should be used deliberately rather than treating zero as evidence of absence.
The examples change zoom and read a missing speed with default one. Go delete removes a map entry, while Swift assigning nil through an ordinary dictionary subscript removes it. Go map values share their underlying map state when copied; Swift dictionaries have value semantics.
Go: complete program
main.go
package main
import (
"fmt"
)
func main() {
settings := map[string]int{"zoom": 2}
settings["zoom"] = 3
zoom, ok := settings["zoom"]
if !ok { zoom = 1 }
speed, ok := settings["speed"]
if !ok { speed = 1 }
fmt.Println(zoom, speed)
}
Swift: complete program
main.swift
import Foundation
var settings = ["zoom": 2]
settings["zoom"] = 3
print("\(settings["zoom"] ?? 1) \(settings["speed"] ?? 1)")Neither Go map nor Swift Dictionary supplies a sorted report contract through ordinary traversal. Sort the keys when presentation order matters.
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 Go 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