Optionals and Binding
Lesson 7 of 48 in Coddy's Swift for Luau Developers course.
Luau writes an optional type as string? and can refine a value after a nil test. The explicit test here preserves empty text. A general or fallback also replaces false, so nil-only defaulting is clearer when false could be a meaningful value. A table field set to nil is removed, not retained as a present nil entry.
Swift String? likewise permits a String or absence. if let unwraps a present value and ?? supplies a nil-only fallback, preserving an empty string. The programs print an empty first line and missing second. Forced unwrapping is not validation: using ! on nil traps.
Luau
Complete Luau console program:
main.luau
local function label(active: boolean): string?
return if active then "" else nil
end
local function display(value: string?): string
return if value == nil then "missing" else value
end
print(display(label(true)))
print(display(label(false)))
Swift
Complete program; compile the listed files together:
Functions.swift
import Foundation
func label(_ active: Bool) -> String? { active ? "" : nil }main.swift
import Foundation
print(label(true) ?? "missing")
print(label(false) ?? "missing")Challenge
EasyImplement 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") }
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 RulesPractice on your own: Swift playground