Menu
CoddyTech

Optionals and Binding

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

GDScript Dictionary.get can return null for a missing key or supply an explicit default. An entry may itself store null, so has is needed when that distinction matters. Zero, false and empty text are separate valid values and should not be discarded by an imprecise absence test.

Swift represents optionality in the type: Int? may contain an integer or nil, while Int requires a value. if let introduces an unwrapped binding, and ?? supplies a fallback only for absence. A forced unwrap of nil traps rather than returning a safe default.

Both dictionary examples preserve the stored zero and use nine for the missing key. Swift text parsing through Int(text) also returns an Optional, making explicit handling useful beyond collection access.

Complete GDScript comparison program:

extends SceneTree

func _init():
    var counts = {"seen": 0}
    var value = counts.get("seen")
    if value != null:
        print(value)
    print(counts.get("new", 9))
    quit()

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 GDScript Developers

Practice on your own: Swift playground