Menu
CoddyTech

Dictionaries and Missing Keys

Lesson 21 of 48 in Coddy's Swift for Java Developers course.

Java Map.get returns null for an absent mapping, which may be ambiguous when null values are permitted. Swift Dictionary lookup returns an optional value. Use optional binding or a fallback to handle a missing key.

This example changes a device setting and reads an absent setting with a default. Swift dictionary keys must conform to Hashable. Assigning nil through a dictionary subscript removes that key. Iterate sorted keys when output order matters; neither a Java HashMap nor a Swift Dictionary promises the desired sorted presentation.

Java: complete program

Main.java

import java.util.*;
import java.util.function.*;
public class Main {

  public static void main(String[] args) throws Exception {
    Map<String, Integer> settings = new HashMap<>();
    settings.put("zoom", 2);
    settings.put("zoom", 3);
    System.out.println(settings.getOrDefault("zoom", 1) + " " + settings.getOrDefault("speed", 1));
  }
}

Swift: complete program

main.swift

import Foundation
var settings = ["zoom": 2]
settings["zoom"] = 3
print("\(settings["zoom"] ?? 1) \(settings["speed"] ?? 1)")

A Swift dictionary defaulted subscript can supply or update a missing value, but an ordinary lookup still returns an optional. Do not force unwrap merely because existing sample input happened to contain the key.

challenge icon

Challenge

Easy

Implement 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") }
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Swift for Java Developers

Practice on your own: Swift playground