Menu
CoddyTech

Failable Initialization

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

Go has no dedicated constructor syntax; a factory function can return a value plus a success flag or an error. Swift init? supplies a failable initializer directly and returns an Optional instance, with nil for rejected construction.

The source returns a zero Slug with false and its caller checks the flag before treating the data as a valid slug. Swift must initialize all stored properties on every successful path. A custom initializer defines the intended construction interface.

Go: complete program

slug.go

package main
type Slug struct { Text string }
func makeSlug(text string) (Slug, bool) { if text == "" { return Slug{}, false }; return Slug{Text: text}, true }

main.go

package main
import (
    "fmt"
)

func main() {
slug, ok := makeSlug("")
    if ok { fmt.Println(slug.Text) } else { fmt.Println("invalid") }
}

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")

Do not confuse the Go zero value on failure with a valid domain object. A failed Swift init? provides no successful instance, and a throwing initializer can preserve a more detailed failure reason.

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 Go Developers

Practice on your own: Swift playground