Menu
CoddyTech

Failable Initialization

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

C# constructors establish an instance or throw; a constructor cannot return null. A named factory can return null or expose a Try pattern to report invalid input. Swift init? builds a value only when its invariant holds and otherwise returns nil. A successful initializer must initialize every stored property before it finishes. Here a nonempty tag is required, rather than checking seat coordinates. A failable initializer is useful when invalid external data is ordinary and callers can branch on absence. Use throwing initialization when a caller needs the specific reason for failure. Do not force-unwrap a construction unless another invariant guarantees success.

C#

Complete program file: Program.cs.

using System;
using System.Collections.Generic;
using System.Linq;
sealed class Tag { public readonly string Text; private Tag(string text) { Text = text; } public static Tag Create(string text) { return text.Length == 0 ? null : new Tag(text); } }

class Program
{
    static void Main()
    {
        var tag = Tag.Create("");
        Console.WriteLine(tag == null ? "invalid" : tag.Text);
    }
}

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