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 Swift Enums and Structs Structs and their Methods Initializers

Why named parameters aren't used when overriding swift struct initializers?

For Swift struct initializers, why is it unncesary to explicitly use the named parameters (such as #firstName, and #lastName) syntax when overriding init function?

struct Contact { 
  // Let will ensure values cannot be reassigned after initialization 

  let firstName: String
  let lastName: String
  var type: String = "Friend"

  init(#firstName:  String, #lastName: String) {
    self.firstName =firstName
   self.lastName = lastName
   self.type = type
  }

1 Answer

Francisco Navarro
Francisco Navarro
14,185 Points

Hi Kevin, I have found this in apple documentation. I haven't realised it until your question but now we know they have a particular role :). Hope that helps.

"Local and External Parameter Names

As with function and method parameters, initialization parameters can have both a local name for use within the initializer’s body and an external name for use when calling the initializer.

However, initializers do not have an identifying function name before their parentheses in the way that functions and methods do. Therefore, the names and types of an initializer’s parameters play a particularly important role in identifying which initializer should be called. Because of this, Swift provides an automatic external name for every parameter in an initializer if you don’t provide an external name yourself."

Had a heard time finding this in the HTML version of the book, for some reason; do you mind sending me a link?

I saw it odd, when it was still validating as correct if I explicitly defined my named parameters (as you should for convenience initializers you may want to create).

Francisco Navarro
Francisco Navarro
14,185 Points

Of course I don't mind. Here's the link:

https://developer.apple.com/library/ios/documentation/swift/conceptual/Swift_Programming_Language/Initialization.html

With the left menu Initialization selected, look for "Local and External Parameter Names" header.