This page requires JavaScript.

Please turn on JavaScript in your browser and refresh the page to view its content.

  • Stack Overflow Public questions & answers
  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Talent Build your employer brand
  • Advertising Reach developers & technologists worldwide
  • Labs The future of collective knowledge sharing
  • About the company

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

How can I initialize a struct or class in Swift?

I have a struct called Person in this code in the down, I am creating an instance of it, like this one:

But I noticed that we can make it with this code as well:

So what is the difference? When I should use first way and when I should use second way?

aheze's user avatar

3 Answers 3

This is the Swift equivalent of what JS calls an Immediately invoked funciton expression (IIFE)

{ Person(name: "Dan", age: 21) } is a closure, of type () -> Person .

{ Person(name: "Dan", age: 21) }() calls this closure, passing no arguments (since it has no parameters), and returns the new Person . The result evaluated to just a Person .

You could nest this any number of times. You could even do:

But there's obviously no point. You code would be most idomaticly written as:

Alexander's user avatar

  • Good answer; upvoted. But you should answer then “when should I” with some variation of, “when you need multiple lines of code”. –  user652038 Apr 21, 2021 at 2:49
  • That's a good point. You should add an answer, I'll up-doot it –  Alexander Apr 21, 2021 at 2:52

The anonymous closure is an unnamed function. It's useful whenever you want to initialize something with the result of calling a function, but you don't want to write a function like:

That would mean you have to come up with a name for the function and find some place to put it, which means it's also visible and can be called by other pieces of code that don't need anything to do with makeDan. It's often useful to have functions that have no names.

Needing a function to initialise something is useful when you have something complex that needs some kind of computation, so multiple lines of stuff. It's also useful when the initialization is only wanted to be done if/when required:

Perhaps because the computation is expensive in some kind of resource use, like cpu or memory. Or possibly because the computation involves some kind of side effect, like opening a database or something, that's only wanted if/when the property is used.

Shadowrun's user avatar

When you want to perform multiple operations while initializing, using closures will help you keep the code clean. See example snippet below -

In the above example, person1 and person3 are initialozed with different initilizers, but person 2 assigns the maritalStatus property differently.

Now consider initializations when you want to change mulitple properties on a object, for example UIView - initializing it, changing the corner radius, assigning a background view, adding pre-selected sub views etc., such closure style of initialization is very helpful.

RPasad's user avatar

Your Answer

Sign up or log in, post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct .

Not the answer you're looking for? Browse other questions tagged swift or ask your own question .

  • The Overflow Blog
  • If you want to address tech debt, quantify it first
  • Fighting comment spam at Facebook scale (Ep. 602)
  • Featured on Meta
  • Moderation strike: Results of negotiations
  • Our Design Vision for Stack Overflow and the Stack Exchange network
  • Call for volunteer reviewers for an updated search experience: OverflowAI Search
  • Discussions experiment launching on NLP Collective
  • Temporary policy: Generative AI (e.g., ChatGPT) is banned

Hot Network Questions

  • Ask for a reduction in conference registration fees
  • How to appease the Goddess of Traffic Lights
  • Forward definition of measurability
  • Selecting diode with Vf~300mV at 100uA forward current for reproducing a zero crossing published TI circuit
  • Is "abreast a" something ever correct?
  • Calculate the Distance to a Line Segment
  • Imbler v. Pachtman and Texas prosecutor Ken Anderson
  • Drawing Asteroids DVG vector objects
  • People who can't receive O negative blood?
  • Why were passengers asked to leave infant boarding pass on the seat when leaving then plane?
  • Is declining an offer to give a talk at a conference halfway around the world a bad idea?
  • Why are stars made from hydrogen and helium and not other elements?
  • Who is this Daft Punk looking character?
  • What do the white circle and black arrow on the airport chart mean? (VOR identifier and frequency written)
  • Finding which process is reading from disk constantly on FreeBSD
  • How to reduce an LP problem already in its standard form?
  • How do I stop a removable valve core from leaking?
  • How to type this character from 汉字大字典 in my computer?
  • Given the parity of a function, how can I find the value of a parameter?
  • How to add the “thriller” in a supernatural thriller?
  • C++20's std::views::filter not filtering the view correctly
  • Sustainable eating habits as a pilot
  • Looking for a series of books that starts with a girl looking in her fridge, realizing she doesn’t like what’s in there and switches it
  • What makes a good alternative to flipping a coin for 50/50 randomness?

struct initialization swift

Your privacy

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy .


Swift How to Initialize a Struct (No ‘init’ with Structs?)

struct initialization swift

To initialize a struct in Swift, you do not need to write the init method. This is because, by default, there is a memberwise initializer that does the job behind the scenes.

For instance:

As you can see, this structure does not implement an init method. But you can create a Fruit object like this:

This is because Swift auto-generates an initializer for a struct.

In this guide, you learn how to use the auto-generated memberwise initializer in Swift structures.

Memberwise Initializer in Swift Structs

In Swift, all structs come with a default initializer. This is called the memberwise initializer.

A memberwise initializer assigns each property in the structure to self . This means you do not need to write an implementation for an initializer in your structure.

Now let’s instantiate a Fruit object:

This works because you instantiate an object, and the memberwise initializer runs behind the scenes. It assigns each argument value to the related property in the structure.

When using a memberwise initializer, you need to provide values (or nils ) to all the properties of the structure. Otherwise, the initialization fails.

For example, let’s try to create a Fruit object by only specifying a name for it:

This results in an error:

As you can see, Swift expects you to provide values for all the properties inside the Fruit structure.

If you do not want to give values to the other properties, you can pass nil as the undefined values:

For instance, let’s create Fruit by only specifying a name :

Another way to overcome the issue is by actually writing a custom initializer to the structure.

For instance, let’s write an initializer for the Fruit structure that defaults the properties to nil :

Now you can create Fruit objects without having to provide each property a value.

For example, let’s create Fruit objects with a varying number of arguments:

Now you understand what is a memberwise initializer in Swift.

Next, let’s take a look at what happens to the memberwise initializer when you write a custom initializer to the structure.

Add a Custom Initializer without Losing Memberwise Initializer

When you write a custom initializer for a struct in Swift, the memberwise initializer goes away.

For example, let’s create a Fruit structure with a custom initializer:

Now you can only initialize a Fruit object by giving it the arguments as a comma-separated string.

For example:

It is not possible to use the default initializer like this:

This error is thrown because as we have a custom initializer, the default initializer is gone for good.

However, there is a way to keep the default initializer in place even after writing a custom initializer.

To do this, write the custom initializer in an extension .

Now the Fruit structure has two initializers:

  • The default memberwise initializer
  • The custom initializer

This means it is possible to use both to create new Fruit objects.

Now you understand how initializers work with structures in Swift.

Memberwise Initializer in a Class?

In Swift, a class does not have a default initializer.

This results in the following error:

The error message is pretty clear. The Fruit class does not have an initializer that could be used to initialize a Fruit object.

Today you learned how to initialize a struct in Swift.

To recap, a structure comes with a default initializer called a memberwise initializer. This makes it possible to instantiate objects without implementing an init method to the structure.

When you write a custom initializer to a structure, the memberwise initializer is gone.

To write a custom initializer and keep the default one, write the custom initializer into an extension .

Thanks for reading. Happy coding!


  1. struct init

    struct initialization swift

  2. Struct's Memberwise Initializer in Swift

    struct initialization swift

  3. Swift Struct Tutorial with Code Examples

    struct initialization swift

  4. Swift Struct vs. Class: Here’s How to Decide Which to Use

    struct initialization swift

  5. Swift

    struct initialization swift

  6. objective c

    struct initialization swift


  1. UIKonf 15

  2. structs arrays

  3. How to create struct in golang

  4. Dymanic Struct Array. #coding #programmingtips#computersciencecourse#code#programmingchallenge

  5. Swift

  6. Swift programming language for the absolute beginner Part 13


  1. Initialization

    Initialization is the process of preparing an instance of a class, structure, or enumeration for use. This process involves setting an initial value for each stored property on that instance and performing any other setup or initialization that’s required before the new instance is ready for use.

  2. Structures and Classes

    The simplest form of initializer syntax uses the type name of the class or structure followed by empty parentheses, such as Resolution() or Video Mode(). This creates a new instance of the class or structure, with any properties initialized to their default values. Class and structure initialization is described in more detail in Initialization.

  3. How can I initialize a struct or class in Swift?

    1 This is the Swift equivalent of what JS calls an Immediately invoked funciton expression (IIFE) { Person (name: "Dan", age: 21) } is a closure, of type () -> Person. { Person (name: "Dan", age: 21) } () calls this closure, passing no arguments (since it has no parameters), and returns the new Person. The result evaluated to just a Person.

  4. Swift How to Initialize a Struct (No ‘init’ with Structs?)

    In Swift, all structs come with a default initializer. This is called the memberwise initializer. A memberwise initializer assigns each property in the structure to self. This means you do not need to write an implementation for an initializer in your structure. For instance: struct Fruit { let name: String? let color: String? let weight: Double? }

  5. How to add a custom initializer to a struct without losing

    All structs in Swift come with a default memberwise initializer, which is an initializer that accepts values for all the properties in the struct. However, as soon as you add your own initializer to the struct that memberwise initializer goes away, because it’s possible you’re doing special work that the default initializer isn’t aware of.