Menu
CoddyTech

Failable Initialization

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

A C++ constructor establishes an object or reports failure through an allowed mechanism such as throwing; it cannot directly return an empty optional. A named factory can return std::optional<Tag>, as shown. Swift init? directly offers failable initialization and produces nil when validation rejects the input. Every successful Swift initialization path must establish stored properties, and failed construction does not expose a partly initialized instance. Use throwing initialization when the caller needs a specific error reason rather than mere absence. Avoid force-unwrapping an ordinary invalid-input path; branch on the optional result instead.

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>
struct Tag {
    std::string text;
    static std::optional<Tag> create(const std::string &text) {
        if (text.empty()) return std::nullopt;
        return Tag{text};
    }
};

int main() {
auto tag = Tag::create("");
    std::cout << (tag ? tag->text : "invalid") << '\n';
}

Swift

Complete program file: Tag.swift.

struct Tag {
    let text: String
    init?(_ value: String) {
        guard !value.isEmpty else { return nil }
        text = value
    }
}

Complete program file: main.swift.

let tag = Tag("")
print(tag?.text ?? "invalid")
challenge icon

Challenge

Easy

Implement Seat(row:column:) as a value type with failable initializer init?(row: Int, column: Int). Accept rows 1 through 20 and columns 1 through 6. Store immutable row and column and expose label: String as row:column. Input has row -5 through 25 and column -5 through 10. Output label 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 Seat.swift, 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 Seat(row: 7, column: 4)?.label == "7:4" && Seat(row: 0, column: 1) == nil && Seat(row: 1, column: 0) == nil && Seat(row: 20, column: 6)?.row == 20
}
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