In addition to the init()
method, we can also provide our structs with custom methods that instances can call. These instance methods are created like a normal function but within the scope of the structure itself:
struct Dog { var age : Int var isGood : Bool init(age: Int, isGood: Bool) { self.age = age self.isGood = isGood } // We've added a bark() method: func bark() { print("woof") } }
In the example above, we added a method bark()
using the func
keyword — it doesn’t have any parameters, nor does it return anything. Although the method syntax looks exactly like a function, the major difference is that a method is specific to the structure’s instances.
Great, now we can create an instance of Dog
that has the .bark()
method:
var bucket = Dog(age: 4, isGood: true) bucket.bark() // Prints: woof
After we defined our instance, bucket
, we can call the method using dot syntax and a pair of parentheses after the method name.
Instructions
Create an instance method inside Band
called pumpUpCrowd
:
- The
pumpUpCrowd()
method should not have any parameters and returns aString
. - Inside the
pumpUpCrowd()
method, return an empty string (""
) for now.
Inside the body of the method:
- Check if
self.isActive
istrue
. - If it evaluates to
true
, return"Are you ready to ROCK?"
. - Otherwise, return
"..."
.
Create an instance of Band
called fooFighters
that takes the arguments:
genre: "rock"
.members: 6
.isActive: true
.
Print out the returned value of calling the .pumpUpCrowd()
on fooFighters
.
What do you think will print?