Menu
CoddyTech

Failable Initialization

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

Rust commonly uses an associated constructor returning Option<Self> or Result<Self, E> to validate creation. Private fields can prevent callers outside the module from bypassing that constructor with a struct literal. Swift init? integrates absence into initialization and returns an optional instance; a throwing initializer is a separate choice when callers need a failure reason. Every successful Swift path must initialize stored properties, and failure must not be treated as a successful partial value. Both factories reject empty text and preserve ok. The coordinate task has its own invariant, so validate its values rather than assuming well-typed arguments are automatically valid domain data.

Rust

mod label {
    pub struct Label { text: String }
    impl Label {
        pub fn new(text: &str) -> Option<Self> {
            if text.is_empty() { None } else { Some(Self { text: text.into() }) }
        }
        pub fn text(&self) -> &str { &self.text }
    }
}

fn main() {
    println!("{}", label::Label::new("").is_none());
    let valid = label::Label::new("ok");
    println!("{}", valid.as_ref().map(|value| value.text()).unwrap_or("missing"));
}

Swift

struct Label {
    let text: String
    init?(_ text: String) {
        guard !text.isEmpty else { return nil }
        self.text = text
    }
}
print(Label("") == nil)
print(Label("ok")?.text ?? "missing")
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 Rust Developers

Practice on your own: Swift playground