Optionals and Binding
Lesson 7 of 48 in Coddy's Swift for C Developers course.
C pointers can be null, but the pointer type alone does not separate nullable and guaranteed-present references. Swift String? explicitly permits absence while String requires a value. An Optional carries either no wrapped value or one value, rather than relying on a raw-address sentinel.
The source tests its pointer before passing text to puts. Swift if let unwraps the optional into a nonoptional local on the success path, and ?? can supply a fallback. Presence is separate from an empty string, whose C buffer still has an address and whose Swift value is not nil.
C: complete program
main.c
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
int main(void) {
const char *nickname = NULL;
puts(nickname != NULL ? nickname : "Unnamed");
return 0;
}
Swift: complete program
main.swift
import Foundation
let nickname: String? = nil
if let name = nickname {
print(name)
} else {
print("Unnamed")
}A nonnull C pointer may still be invalid if its storage has expired. Swift optional handling is a typed absence model, not a substitute spelling for unchecked pointer dereference.
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 C 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