Optionals and Binding
Lesson 7 of 48 in Coddy's Swift for PHP Developers course.
PHP ?? supplies a default when an expression is missing or null while preserving zero, false and empty text. isset likewise reports false for null, whereas array_key_exists can distinguish a present null entry from a missing key. Nullable parameter types express permitted null values, but ordinary locals remain dynamically typed.
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 lookups preserve the recorded zero and use nine for a missing key. Swift represents lookup absence in an Optional type, and its integer parser also returns an optional. Check which distinctions the source API preserves before mapping missing and null states into a single target absence case.
Complete PHP comparison program:
<?php
declare(strict_types=1);
$counts = ["seen" => 0];
$value = $counts["seen"] ?? null;
echo $value ?? 9, "\n";
echo $counts["new"] ?? 9, "\n";
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
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 PHP 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