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 trialMatt Conway
1,572 PointsMethods
Wonder why this isn't working?
Challenge Task 2 of 2
We learned about instance methods before. For this task, add an instance method to Post.
Name the method description. It takes no parameters and returns a string that describes the post instance. For example given a title: "iOS Development", author: "Apple", and a tag named "swift", the description would read as follows"
"iOSDevelopment by Apple. Filed under swift"
Once you have an instance method, call it on the firstPost instance and assign the result to a constant named postDescription
/Users/mattconway/Desktop/Screen Shot 2016-01-28 at 6.51.18 PM.png
struct Tag {
let name: String
}
struct Post {
let title: String
let author: String
let tag: Tag
}
let tagX = Tag(name: "TagX")
let firstPost = Post(title: "Treehouse", author: "Pasan", tag: tagX)
let description = Post(title: "Treehouse", author: "Pasan", tag: tagX) -> [Post] {
print("\("title") by \("author"). Filed under \(tagX)")
}
let postDescription = firstPost
1 Answer
Michael Reining
10,101 PointsHi Matt,
The instance method has to be added into the definition of the struct and the syntax to create a method is fun (a method is just like a function)
Make sure the method returns a string
Make sure to return the tag.name and not just the tag object
Once you do the above, you end up with this.
struct Tag {
let name: String
}
struct Post {
let title: String
let author: String
let tag: Tag
// create instance method
func description() -> String { // return string
return "\(title) by \(author). Filed under \(tag.name)" // return tag.name
}
}
let tagX = Tag(name: "TagX")
let firstPost = Post(title: "Treehouse", author: "Pasan", tag: tagX)
let postDescription = firstPost.description() // call instance method and assign to constant
I hope that helps,
Mike
PS: Thanks to the awesome resources on Team Treehouse, I launched my first app.
Now you can practice writing Swift code directly on your iPhone :-)