Menu
CoddyTech

Optionals and Binding

Lesson 7 of 48 in Coddy's Swift for Ruby Developers course.

Ruby Hash lookup commonly returns nil for a missing key, but a hash may also store nil or use a custom default. Fetch with a default distinguishes a missing key from a present nil value. The || fallback replaces both nil and false, while a nil? test preserves a meaningful false.

Swift represents possible absence in the type with Optional, written T?. if let binds a present value, and ?? supplies a fallback only for nil. Neither a present zero nor a present false is discarded. A forced unwrap traps when the optional is nil and should not be used to validate input.

Both examples preserve a stored zero and default a missing entry. Swift dictionary lookup makes absence explicit with Optional, and ?? only substitutes for nil. If the source distinguishes missing, present nil and a custom default, model those states deliberately instead of collapsing them accidentally.

Complete Ruby comparison program:

counts = {"seen" => 0}
value = counts["seen"]
puts(value.nil? ? 9 : value)
puts counts.fetch("new", 9)

Complete Swift comparison program, compiled from these files:

main.swift

let counts = ["seen": 0]
let value = counts["seen"]
if let number = value { print(number) }
print(counts["new"] ?? 9)
challenge icon

Challenge

Easy

Implement port(_:) -> Int?: return a parsed integer only in 1 through 65535, otherwise nil. Input is one nonempty ASCII token of at most 10 characters, either decimal digits, an optional leading minus, or letters. Output the value or invalid.

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 port("443") == 443 && port("0") == nil && port("oops") == nil && port("65536") == nil
}
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 Ruby Developers

Practice on your own: Swift playground