Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

Is the following a valid definition of the init method?

Hello everyone,

I'm going through the struct videos and at the end I have this quiz. One of the questions I don't know why the provided code isn't valid.

struct Task { var description: String var completed: Bool

init() {
  self.completed = false
}

}

Can anyone tell me the valid way to initiate a struct?

1 Answer

Your init method is totally fine. Except your initializer should initialize all the stored properties.

struct Task { 
   var description: String 
   var completed: Bool

   init() {
      self.completed = false
      self.description = "a description"
   }
}

if you want the user of this struct to specify the values, don't add an init method. A struct by default gives you an initializer.

let task = Task(description: "a description", completed: true)

The initialization of a struct is similar to the initialization of a class

let task = Task()

Thank you! That solved my problem.

Anytime Brian :)