Skip to Content
Learn
Structures
Structure Methods

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. The method syntax looks like exactly of function, the major difference being 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

1.

Create an instance method inside Band called pumpUpCrowd:

  • The pumpUpCrowd() method should not have any parameters and returns a String.
  • Inside the pumpUpCrowd() method, return an empty string ("") for now.
2.

Inside the body of the method:

  • Check if self.isActive is true.
  • If it evaluates to true, return "Are you ready to ROCK?".
  • Otherwise, return "...".
3.

Create an instance of Band called fooFighters that takes the arguments:

  • genre: "rock".
  • members: 6.
  • isActive: true.
4.

Print out the returned value of calling the .pumpUpCrowd() on fooFighters.

What do you think will print?

Folder Icon

Take this course for free

Already have an account?