Menu
CoddyTech

Optionals and Binding

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

C++17 std::optional<T> stores either a T value or no value, making it a useful comparison to Swift Optional<Wrapped>. A C++ optional can be tested contextually for engagement, but Swift requires optional binding, matching or an explicit nil comparison rather than general optional truthiness. Both can preserve a present zero separately from absence. C++ dereferencing a disengaged optional is invalid, and value() reports missing engagement by throwing; Swift forced unwrap of nil traps. Use deliberate fallback or binding when absence is ordinary. Swift Optional can wrap class references as well as values, while C++17 optional does not directly instantiate with a reference type.

C++

Complete program file: main.cpp.

#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <optional>
#include <memory>
#include <tuple>
#include <variant>
#include <stdexcept>
#include <algorithm>

int main() {
std::optional<int> width;
    std::cout << width.value_or(80) << '\n';
    width = 24;
    if (width) std::cout << *width << '\n';
}

Swift

Complete program file: main.swift.

var width: Int? = nil
print(width ?? 80)
width = 24
if let actual = width { print(actual) }
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 C++ Developers

Practice on your own: Swift playground