Dictionaries and Missing Keys
Lesson 21 of 48 in Coddy's Swift for R Developers course.
Assigning NULL with double-bracket list replacement removes that element in R. Single-bracket replacement with list(NULL) can instead preserve a present NULL element. Names can be inspected when missing versus present-null matters. Length counts list elements, not the character count of their names.
Swift Dictionary is a typed key-value collection. Its subscript returns an optional, and assigning nil through that subscript removes the entry. A default can be supplied with ??; count gives the entry count. Sort the keys explicitly when an output requires ascending order.
Both examples remove gap and use eight for the absent lookup. Swift Dictionary has typed keys and optional subscript results, rather than R's flexible named-list shape. Ensure a port preserves any meaningful source distinction among absent, NULL and NA values.
Complete R comparison program:
settings <- list(font = 14L, gap = 2L)
settings[["gap"]] <- NULL
value <- settings[["gap"]]
cat(if (is.null(value)) 8L else value, "\n", length(settings), "\n", sep = "")
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
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 R 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