Learn
Structures
Memberwise Initialization

In the previous exercise, we’ve explicitly provided an init() method inside our struct. Structures also come with a built-in memberwise initializer that can be used to assign values upon instance creation. So in certain cases, we don’t actually need to use init()!

Let’s remove the init() method from Dog and take a look our code again:

struct Dog { var age: Int var isGood: Bool }

Using the memberwise initializer, we can create another instance:

var eloise = Dog(age: 5, isGood: true)

Notice that we didn’t need an init() method to provide initial values — but, we still have to provide arguments for all the initial values! It’s still important that we pass in the arguments in the order that matches the ordering of the properties in the Dog structure.

While it’s harder for other developers to know exactly what our code means without an init() method (decreased readability), we now have a convenient means of initializing instances. Another positive is that it’s great if we don’t need to manipulate the provided argument(s).

Instructions

1.

Create a struct called Band that has three properties:

  • genre of type String.
  • members of type Int.
  • isActive of type Bool.
2.

Under the struct definition, create an instance of Band called maroon5 that takes the arguments:

  • genre with a value of "pop".
  • members with a value of 5.
  • isActive with a value of true.
Folder Icon

Take this course for free

Already have an account?