Initializers are the special methods that prepare a new instance of a type for use by giving every stored property a starting value. This repository is a short, runnable learning example that walks through the different ways a Swift struct can be initialized — from the free memberwise initializer to custom init() methods and initializers added through extensions.
- Memberwise initializers — the automatic initializer a struct gets for free based on its stored properties.
- Custom initializers — writing your own
init()to assign values and run setup logic such as aprint. - Default property values — how a default makes the matching argument optional at the call site.
- Using
self— disambiguating a stored property from a parameter inside an initializer. - Initializers in extensions — adding an
init()in an extension so the synthesized memberwise initializer is kept alongside it.
git clone https://github.com/ahmetbostanciklioglu/Initializers.git
cd InitializersPaste the snippet from README.md into an Xcode Playground (or a .swift file) and run it to watch each initializer create its instance.
- Swift 5+
- Xcode 12 or later (an Xcode Playground is enough)
Ahmet Bostancıklıoğlu — @ahmetbostanciklioglu · ahmetbostancikli@gmail.com
⭐ If this helped you, consider giving the repo a star!