Menu
CoddyTech

Failable Initialization

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

GDScript _init initializes a new object and does not act as a Swift optional-returning initializer. A separate factory can check inputs and return null when absence is the chosen contract. The source uses that explicit factory instead of pretending _init can reject construction by returning null.

Swift init? produces an Optional instance and can return nil on a failure path. Every successful path must initialize all stored properties. Use optional binding or a deliberate fallback, and use a throwing initializer instead when the caller needs a precise failure reason.

Both examples reject an empty suffix and print missing. Correct argument types alone do not prove a domain invariant, so callers must handle ordinary invalid input.

Complete GDScript comparison program:

extends SceneTree
class Suffix:
    var text: String
    func _init(value: String):
        text = value
func make_suffix(text: String):
    if text.is_empty():
        return null
    return Suffix.new(text)

func _init():
    var value = make_suffix("")
    print("missing" if value == null else value.text)
    quit()

Complete Swift comparison program, compiled from these files:

Suffix.swift

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

main.swift

let value = Suffix("")
print(value?.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 GDScript Developers

Practice on your own: Swift playground