Menu
CoddyTech

Dictionaries and Missing Keys

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

GDScript Dictionary is a shared reference container and uses erase to remove an entry. Assigning null stores a null value rather than meaning removal. get can provide a default and has distinguishes an existing key from an absent one even when its value is null.

Swift Dictionary is a value type and ordinary lookup returns an Optional. Assigning nil through the shown dictionary subscript removes its mapping. A defaulted subscript can assist updates, but absence and a stored default may carry different meaning for a particular API.

Both examples delete gap, read eight as the fallback and count one remaining key. Explicitly sort keys when output order matters instead of treating dictionary traversal as the required report order.

Complete GDScript comparison program:

extends SceneTree

func _init():
    var settings = {"font": 14, "gap": 2}
    settings.erase("gap")
    print(settings.get("gap", 8))
    print(settings.size())
    quit()

Complete Swift comparison program, compiled from these files:

main.swift

var settings = ["font": 14, "gap": 2]
settings["gap"] = nil
print(settings["gap"] ?? 8)
print(settings.count)
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 GDScript Developers

Practice on your own: Swift playground