Failable Initialization
Lesson 41 of 48 in Coddy's Swift for C Developers course.
C factories can return status and write an output struct only on success, or return a pointer with a null failure convention. Swift init? is a failable initializer that yields an Optional instance and can return nil when validation rejects the input. It does not expose a partially initialized success value.
The source leaves its output uninitialized on failure, and the caller avoids reading it by checking the status. Swift initializes every stored property on each successful path. This custom struct initializer supplies the intended API rather than relying on synthesized memberwise initialization.
C: complete program
slug.h
#ifndef SLUG_H
#define SLUG_H
#include <stdbool.h>
typedef struct { const char *text; } Slug;
static bool slug_make(const char *text, Slug *result) {
if (text[0] == '\0') return false;
*result = (Slug){text};
return true;
}
#endif
main.c
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include "slug.h"
int main(void) {
Slug slug;
if (slug_make("", &slug)) puts(slug.text); else puts("invalid");
return 0;
}
Swift: complete program
Slug.swift
import Foundation
struct Slug {
let text: String
init?(_ text: String) {
guard !text.isEmpty else { return nil }
self.text = text
}
}main.swift
import Foundation
let slug = Slug("")
print(slug?.text ?? "invalid")Treat construction failure as absence or an explicit error contract. Never read a C output object after a failing status unless its failure-state initialization is explicitly guaranteed.
Challenge
EasyImplement 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") }
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 Rules5Collection Tools
Dictionaries and Missing KeysSets and MembershipUnicode and Character IndicesClosures and TransformationsRecap: Catalog Merge8Designing Types
Inheritance and OverridesComposition Through a PolicyAccess Control and InvariantsEnums with Associated ValuesFailable InitializationRecap: Booking LedgerPractice on your own: Swift playground