A concise, runnable Swift Playground exploring initializers that can return nil.
A failable initializer (init?) lets a type reject invalid input during construction by returning nil instead of a fully formed instance, which is why a call to it produces an optional. This repository is a small, runnable Xcode Playground that demonstrates the concept with two minimal examples: a custom class that validates its input inside init?, and Swift's built-in failable Bool(_:) string initializer. It is meant as a concise learning reference rather than a full app.
- Declaring a failable initializer with
init?on a custom class. - Returning
nilfrom an initializer when a validation condition is not met. - How a failable initializer produces an optional instance at the call site.
- Swift's built-in failable
Bool(String)initializer, which yieldsnilfor anything other than"true"/"false".
git clone https://github.com/ahmetbostanciklioglu/FailableInitialize.git
cd FailableInitialize
unzip FailableInitialize.playground.zip
open FailableInitialize.playgroundOpen the .playground in Xcode and press Command-R (or let it run) to see each line evaluate live in the results sidebar.
- Xcode 13 or later
- Swift 5
- iOS Playground target
Ahmet BostancΔ±klΔ±oΔlu β @ahmetbostanciklioglu Β· ahmetbostancikli@gmail.com
β If this helped you, consider giving the repo a star!