Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

iOS Swift Enums and Structs Structs and their Methods Struct Methods

Dawn Tan
Dawn Tan
1,366 Points

The Preview panel didn't return any errors. I'm not sure where I went wrong with my answer

Please enlighten me!

struct.swift
struct Expense {
    var description: String
    var amount: Double = 0.0

    init (Description: String, Amount: Double) {
        self.description = Description
        self.amount = Amount
    }

    func calculateTaxes (percentage: Double )-> Double? {
      return (self.amount * (percentage/100))
    }

}
var item = Expense(Description: "Whatever", Amount: 100)
//item.amount = 100.0

1 Answer

Hi Dawn,

There's a couple of points here:

  • The question isn't expecting you to amend the initializer
  • The calculateTaxes function should return a Double not an optional

Your code will work fine in the preview panel as that shows compiler errors. What it doesn't show is the output of the other tests that check the challenge has been answered as expected. That makes the challenges especially tricky as they are expecting the question to be answered in a particular way, not necessarily just by writing 'correct' code.

So, the answer tests will be looking for the amount member variable to be assigned on a separate line, for example.

The input code that completes the challenge, entered question by question looks like:

struct Expense {
    var description: String
    var amount: Double = 0.0

    init (description: String) {
        self.description = description
    }

    // add the calculateTaxes method here
    // it should accept only one parameter named 'percentage' of type Double
    func calculateTaxes(percentage: Double) -> Double{
      return (self.amount * (percentage / 100))
    }
}

var item = Expense(description: "Hotel")
item.amount = 100
var taxes = item.calculateTaxes(7.5)

At this stage, the questions are deliberately quite explicit in how to answer the question - alternative routes are possible but they may cause the challenge to fail as the answer input may not match the precise order expected.

I hope that helps,

Steve.