iOS Build a Simple iPhone App with Swift Getting Started with iOS Development Swift Recap Part 1

Jed Odagbu
Jed Odagbu
1,162 Points

Code challenge keeps saying there are errors in my code and I should check the compiler

When I check preview, no error shows up and my code runs fine on Xcode but not in the code challenge

structs.swift
struct Tag {
  let name: String
}

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

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

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

}

let firstPost = Post(title: "iOSDevelopment", author: "Apple")
let postDescription = firstPost.description()

2 Answers

Jhoan Arango
MOD
Jhoan Arango
Treehouse Moderator 13,603 Points

Hello Jed,

Remember that when you create a struct, you do not need to add an initializer unless you decided to do it. When you add an initializer, you lose the member-wise initializer that the struct brings by default. I am not saying this is a mistake on how you are writing your code, because the way you did it is acceptable and correct, but maybe the treehouse compiler is not catching this and returning as an error. One way to not lose your initializer, is to extend the struct and create your custom initializer there. This way you will have both options. Also, as an observation, the properties in this particular case should be constants instead of variables. These values should not change nor they are optionals, therefore the constant makes more sense.

So try eliminate the init, and try the challenge again. Let me know if that worked.

struct Tag {
  let name: String
}

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

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

}

let firstPost = Post(title: "iOSDevelopment", author: "Apple", tag: Tag(name: "swift"))
let postDescription = firstPost.description()
Jed Odagbu
Jed Odagbu
1,162 Points

Thanks, it worked. Much appreciated