Dictionaries and Missing Keys
Lesson 21 of 48 in Coddy's Swift for Kotlin Developers course.
Kotlin Map lookup returns a nullable value when a key is missing. Swift Dictionary lookup similarly returns an Optional, even when the stored Value type itself is nonoptional. Use optional binding or a fallback when absence is valid. Swift also offers a subscript with a default value, which is especially useful for updating counters, but a plain read through that subscript does not insert the missing key. Dictionary traversal order is not a suitable output contract; sort keys when a deterministic report is required. The example reads a known key and a missing key while checking that fallback reads leave the dictionary unchanged.
Kotlin
fun main() {
val ages = mapOf("Mina" to 12)
println(ages["Mina"] ?: -1)
println(ages.getOrDefault("Jo", 99))
println(ages.size)
}Swift
let ages = ["Mina": 12]
print(ages["Mina"] ?? -1)
print(ages["Jo", default: 99])
print(ages.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 Kotlin 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