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
Manuel Schulze
12,739 PointsSwift - Extra Credit
Hey guys, I got a problem with this:
Extra Credit Write a function that accepts a Dictionary as parameter and returns a named tuple. The dictionary should contain the following keys: title, artist and album.
Here is my code:
// Tuples
import UIKit
func music (#song: Dictionary) -> (title: String, artist: String, album: String) {
return (title: song["title"], artist: song["artist"], album: song["album"])
}
var example = ["title": "She's a rebel", "artist": "Green day", "album": "American Idiot"]
var result = music(song: example)
println(result.title)
I got no output and I think there is a problem with the way I pass the dictionary. I'm pretty new to iOS and Swift so I can't fix it.
4 Answers
Brad Van Skyhawk
28,489 Pointsfunc music (song: Dictionary<String,String>) -> (title: String, artist: String, album: String) {
return (title: song["title"]!, artist: song["artist"]!, album: song["album"]!)
}
Not quite sure yet, but this seems to work.
Jason Hernandez Berland
1,575 PointsBrad Van Skyhawk getting 'reference to generic type Dictionary' error . Can you explain the why you added '!' in the return?
Manuel Schulze
12,739 PointsHey jaytova_, I hope that I can help you. You have to add the "!" because you are allowed to pass generic dictionaries. That means they may not have a title, an artist or an album. Xcode is trying to protect you from upcoming errors. If you use the "!" you say: 'I know what I'm doing and I know that I will only pass dictionaries to the function which have at least a title, an album and an artist.'
And then Xcode reacts like this: 'Ok it's fine if you know what you're doing'.
You know what I mean?
Jason Hernandez Berland
1,575 PointsThanks Manuel Schulze . So if I am understanding correctly, if I attempt to pass a dictionary without a title
var example = [ "artist": "Green day", "album": "American Idiot"]
does the "!" prevent my app from crashing and/or will the above dictionary not pass into the function?
Confused as to when to use "!" and when to add "?" to a datatype
Still, I'm getting 'reference to generic type Dictionary' error w/ Brad Van Skyhawk 's code above and it won't compile
Manuel Schulze
12,739 PointsNo, it will not prevent the app from crashing. And your app will crash probably. But with the "!" you say I will only pass dictionaries with at least these attributes that I return. So you see that you have to be very careful while using the "!". Because if you use an exclamation mark you need to know what kind of dictionaries get passed to the function in your whole app.
I would argue that it's like telling Xcode that you know that you're doing something risky and you really want to do this and you take care of.
If you don't tell Xcode explicit it will prevent you from doing this because you may not know what you're doing and that this is a potential risk.
Manuel Schulze
12,739 PointsThank you very much. I hope I will learn in the next stages what the "!" means ;)
But to make it work I had to fix the parameter to:
func music(#song: Dictionary<String, String> -> ...
Anyway thank you for your help.
Daniel Wendt
1,911 PointsMoin Manuel Schulze ,
ich habe jetzt gerade das selbe Problem.....
im Endeffekt habe ich alles ähnlich gemacht wie du, nur sagt er mir ich hätte auch noch einen Fehler der nicht so will wie er soll.....
Dictionary hat den Error : needs arguments in < ... > und wenn ich dann: Dictionary<String,String,String> setze dann Error: ... with too many type parameters (got 3, but expected 2)
Hier ist mein Code:
// Extra Credit Parameters und Tuples
import UIKit
func music( song: Dictionary<String,String,String>) -> (title: String, artist: String, album: String) {
return ( title: song["title"]!, artist: song["artist"]!, album: song["album"]! )
}
var example = [ "title":"Mongo",
"artist":"Mongolen",
"album":"Mongo Album" ]
var result = music(song: example)
println(result)
villt kannst du mir helfen und siehst was dort verkehrt ist!
Danke! ;)
Daniel Wendt
1,911 PointsOk, hab jetzt grade noch mal einiges beseitigt bekommen. JETZT funktioniert es.
Hier der neue Code:
// Extra Credit Parameters und Tuples
import UIKit
func music( song: Dictionary<String,String>) -> (title: String, artist: String, album: String) {
return ( title: song["title"]!, artist: song["artist"]!, album: song["album"]! )
}
var result = music([ "title":"Mongo",
"artist":"Mongolen",
"album":"Mongo Album" ])
println(result)
ABER was mich jetzt interessiert:
Warum muss ich bei song: Dictionary<String,String> nur 2x String setzten obwohl es ja 3 Teile sind.
Was bedeutet die Return-Zeile?! Vorallem mit dem !
Manuel Schulze
12,739 PointsHey Daniel,
ich denke bei dem ersten Teil kann ich dir behilflich sein. Du übergibst ein Dictionary und dieses hat das "Format" <String, String>, denn der Key ist ein String und der Value auch. Die Funktion erwartet hier also kein Dictionary mit den 3 Werten, sondern allgemein ein Dictionary das aus Einträgen mit einem Key (String) und einem Value (String) besteht.
Das zweite versuche ich mal herauszufinden und gebe dir dann Bescheid ;)
Gruß
Manuel Schulze
12,739 PointsOk, ich habe in der Apple Docu nachgeschaut um etwas Licht ins Dunkle zu bringen.
Also erst einmal was heißt die Return-Zeile? Du hast ja bei der Funktionsdefinition angegeben, dass die Funktion ein Tuple mit 3 String Werten zurückgibt. Diese sind benannt mit: title - artist - album. Jetzt in der Return-Zeile nimmst du die Werte aus dem Dictionary das du übergeben hast (und song genannt hast). Und übergibst sie als Tuple.
Was heißen die Ausrufezeichen? Das ist etwas komplizierter. Du kannst ja jedes Dictionary übergeben, auch eines, dass gar nicht den Wert 'title' enthält. Das meldet Xcode als Fehler. Wenn du das Ausrufezeichen nutzt, dann sagst du damit aus, dass du dir ganz sicher bist, dass jedes Dictionary, das du an diese Funktion in deinem Programm übergibst, auch diese Werte gesetzt hat. Dann ignoriert Xcode diesen Code und markiert ihn als erlaubt.
Lange Rede kurzer Sinn, mit dem Ausrufezeichen seeeeeeehr vorsichtig umgehen.
Ich hoffe ich konnte helfen.
Gruß Manu
Daniel Wendt
1,911 Pointsmoin Manuel Schulze,
erstmal großes DANKE! Der erste Post hat mir schonmal weiter geholfen. Jetzt kann ich mir das auch mit 2 Strings vorstellen!
Das mit dem Bang habe ich in dem Video danach dann auch gelernt :D Da habe ich etwas zu früh ins Forum geschossen!
Im nach hinein ist mir dann einiges klarer geworden! Vielen Dank nochmal, ich hoffe ich kann bei evtl. Fragen nochmal auf dich zu kommen ;-)
Viele Grüße Daniel
Manuel Schulze
12,739 PointsKlar immer wieder gern.
Gruß
Edward Kelly
3,705 PointsEdward Kelly
3,705 PointsThe result of each key/value pair might not exist, therefore the result is an Optional. The exclamation point 'unwraps' the Optional.