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

Why can't we just write let areaOfRoom = length x width, since it's nested under a function that accepts those inputs?

Specifically confused about this part:

 let areaOfRoom = area(length: length, width: width)

In the following code:

func area(length: Int, width: Int) -> Int {
    let areaOfRoom = length * width

    return areaOfRoom

func carpetCostHaving(length: Int, width: Int, carpetColor color: String = "tan") -> (Price: Int, carpetColor: String) {

    // Grey Carpet - $1/sqft
    // Tan Carpet - $2/sqft
    // Deep Blue carpet - $4/sqft

    let areaOfRoom = area(length: length, width: width)

    var price = 0

    switch color {
    case "grey": price = areaOfRoom * 1
    case "tan": price = areaOfRoom * 2
    case "deepBlue": price = areaOfRoom * 4
    default: price = 0
    }

    return (price, color)
}

Why can't we just write let areaOfRoom = length x width, since it's nested under a function that accepts those inputs? Would it not just inherit those values?

Edit: I've tried it with length x width and it works. Just wondering what the value is in writing it in this form:

 let areaOfRoom = area(length: length, width: width)

1 Answer

Brandon Adams
Brandon Adams
10,325 Points

Programming is very flexible. So yes, you could do it that way. But what if the method was 20 lines of code? Would you want to type that every time or do a method call? So the point is to show you how to do it with simple code before getting into harder stuff. Good question though.

Makes sense, thanks!