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
Create a struct called Band
that has three properties:
genre
of typeString
.members
of typeInt
.isActive
of typeBool
.
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 of5
.isActive
with a value oftrue
.