Dictionaries and Missing Keys
Lesson 21 of 48 in Coddy's Swift for Luau Developers course.
Luau uses table keys for map entries. Assigning nil removes cache, and pairs can enumerate the remaining keys. The # operator is a sequence-length operation, not a general count of string keys. A stored false remains an entry even though it is falsey; nil and false have different map meanings.
Swift Dictionary lookup returns an optional, and assigning nil through its subscript removes the key. The fallback ?? false handles the absent Boolean here. Count reports entries, and dictionary traversal is not a sorted report contract. Sort keys explicitly whenever the required output depends on their order.
Luau
Complete Luau console program:
main.luau
local flags: {[string]: boolean} = {cache = true}
flags.cache = nil
print(flags.cache or false)
local count = 0
for _ in pairs(flags) do count += 1 end
print(count)
Swift
Complete program; compile the listed files together:
main.swift
import Foundation
var flags = ["cache": true]
flags["cache"] = nil
print(flags["cache"] ?? false)
print(flags.count)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 Luau 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