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 Build a Simple iPhone App with Swift Getting Started with iOS Development Swift Recap Part 1

William Larsten
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
William Larsten
UX Design Techdegree Graduate 17,195 Points

Code challenge issue, working in Xcode...

Hi!

I don't get what I'm doing wrong in this code challenge. I get this to compile and get the correct result in Xcode.

I have a struct with title: String, author: String and tag: Tag as instructed.

I've created an initialized because I don't know how else to get the a string into the tag type...

I have a method that uses string interpolation in order to create the required sentence. However, I'm forced to take tag.name in order to access the string in the tag.

What's gone wrong?

structs.swift
struct Tag {
  let name: String
}

struct Post {
    let title: String
  let author: String
  let tag: Tag

  init(title: String, author: String, tag: String) {
        self.title = title
    self.author = author
      self.tag = Tag(name: tag)
  }

    func description() -> String {
    return "\(title) by \(author). Filed under \(tag.name)"
  }
}

let firstPost = Post(title: "HP6", author: "JKR", tag: "fantasy")

let postDescription = firstPost.description()

1 Answer

Alex Koumparos
seal-mask
.a{fill-rule:evenodd;}techdegree
Alex Koumparos
Python Development Techdegree Student 36,887 Points

Hi William,

Struct instances are first-class in Swift, so you can pass them directly into a method.

Structs also give you an initialiser with all the required properties for free.

For example, if you have the following struct:

struct MyStruct {
    let name: String
}

You can initialise a MyStruct instance by writing

MyStruct(name: "Example Struct")

Thus if you have another struct that takes this type as a parameter, you can pass exactly that in as an argument:

SomeOtherStruct(someProperty: "hello, world", myStructInstance: MyStruct(name: "Example Struct"))

You can pass a Tag instance into built-in Post initialiser the same way.

Hope that's clear

Cheers

Alex

William Larsten
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
William Larsten
UX Design Techdegree Graduate 17,195 Points

Big thanks! I thought I had tried that but I must have used the wrong syntax or something. So then I went on to really overcomplicate things! :)