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 Struct Methods

YI FENG XIE
YI FENG XIE
2,274 Points

when should i use parameters name

struct Test { var age:Int var name: String = "Jason"

init(name: String) {
    self.name = name
    self.age = 12
}

func print(text:String) -> String {
    return text
}

}

var item = Test(name: "AA") // ok var result = item.print("AA”) // ok

var item2 = Test("AA") // raise error var result2 = item.print(text: "AA”) // raise error

My question is both init and print func have same declaration of their parameters but why the first line Test(name: "AA") required param name but item.print("AA”) is not?

1 Answer

Jo Albright
Jo Albright
5,199 Points

So this is a weird but necessary design pattern. Almost all of the functions you create (within classes and structs) will not use the first parameter name... normally because of things like addName(name: String) ... since "name" is part of the function name, there is no need to double up. But there are exceptions and the biggest one is custom init functions... these will always use the first parameter as init(name: String) will never explain what the first parameter is in the function name, so you will see init(name: "Bob").

// naming explains first parameter

func addName(name: String) { }

addName("Bob") // you read this as "add name"

// init need first parameter to make it readable

init(name: String) { }

init(name: "Bob") // you read this as "init with name"

// custom naming for additional parameters

func addFirstName(firstName: String, andLastName lastName: String) { }

addFirstName("Bob", andLastName: "Smith") // you read this as "add first name and last name"
YI FENG XIE
YI FENG XIE
2,274 Points

Make sense~ Thank for your explanation!