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

Blair Rorani
Blair Rorani
6,658 Points

Why do I need to add "" to string parameters manually?

If I'm using the function

carpetCostHaving(length: 10, width: 20, carpetColor: String)

carpetColor: String needs the value for the string to have "" added manually (e.g carpetColor: "red". Why is this if Swift already knows it should expect a string?

1 Answer

I guess a better way to put it is that the compiler requires a string to be the ultimate value there. Swift doesn't necessarily know what you are going to give it. Below is an example where I give it different values.

First a string "Tan". Second is a constant firstColor with the value of "Tan". Third is a constant notAColor with an Int value.

The parameter accepts all three as an argument, but "notAColor" gives an error.

let firstColor = "Tan"
let notAColor = 3

func carpetColorFunc(carpetColor: String) -> String {
    return "My carpet color is \(carpetColor)"
}

print(carpetColorFunc(carpetColor: "Tan"))
//Prints "My carpet color is Tan"

print(carpetColorFunc(carpetColor: firstColor))
//Prints "My carpet color is Tan"

carpetColorFunc(carpetColor: notAColor)
//Does not print, but gives error message "Cannot convert value of type 'Int' to expected argument type 'String'"