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

Calling values of a Function

Hey,

I am currently working on a code challenge and I ran into a problem which I already had a few times. Basically I wanted to know if it's possible to write a function which has default values but also the ability to change it with a normal instance.

So this is the function:

 struct Post {
    let title: String
    let author: String


    func description(title: String = "Hello", author: String = "Treehouse" ) -> (String, String, String) {

            return (title, author, "!")   
    }}

And now I can create an Instance of Post and I am able to change the Strings:

let firstPost = Post.init(title: String, author: String)

So what do I have to do that I get the default values I declared in the function?

1 Answer

If you are trying to create an instance of your Struct without using parameters you need to override your init method. Currently you are adding default parameters to the description method.

struct Post {
    let title: String
    let author: String


    func description(title: String = "Hello", author: String = "Treehouse" ) -> (String, String, String) {

        return (title, author, "!")
    }

  // by adding in an init it will override the default init of the struct
    init(title: String = "Hello", author: String = "Treehouse") {
        self.title = title
        self.author = author
    }
}

// You can then instantiate a new Post without passing parameters
let newPost = Post()

Otherwise your current implementation of description should be able to be called with or without params once you have the instance of a Post().

Give it a try and let me know if you have any questions.

Ah perfect that is the answer I was looking for.

Thank you!