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
David Alvarez
2,689 PointsTrying to make a function. What´s wrong in my code?
Hello:
I´m trying to make a function that return the value in a dictionary when the user insert the key as argument in the function.
functionName(Key) ----> Value
That´s my code:
let keyOfC = [1: "C", 2: "D", 3: "E", 4: "F", 5: "G", 6: "A", 7: "B"]
func scaleTonesC(keyNumber: Int) -> String {
return keyOfC.[keyNumber]
}
But it doesn´t work. What´s wrong in this code?
Thanks
4 Answers
Dalisson Figueiredo
7,731 PointsIt works now.
let keyOfC = [1: "C", 2: "D", 3: "E", 4: "F", 5: "G", 6: "A", 7: "B"]
func scaleTonesC(keyNumber: Int) -> String? { //notice the interrogation mark, you need it because dictionaries are
//optionals.
return keyOfC[keyNumber] // you can change the interrogation mark for an exclamation mark in front of this line
//But force unwrapping is not recommended.
}
Oliver Duncan
16,642 PointsYou can use the non-optional String type, but keep in mind that this can crash your app: keyofC[8] will return nil, which isn't a string value and will therefore throw an exception.
If you don't want to use the optional type, you could try using optional binding:
func scaleTonesC(scaleNumber: Int) -> String {
if let note = keyOfC[keyNumber] {
return note
}
return "Invalid scale degree"
}
This will always return a string, so you can rest easy using the non-optional return type.
David Alvarez
2,689 PointsNice!!
Thanks.
But why can´t use [String] output? If I click alt key and I put over the mouse on the dictionary, I can see [String] type.
David Alvarez
2,689 Pointsok, thanks Oliver