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 trialStijn van Lieshout
3,646 PointsCode passes test but gets "Statements are not allowed at the top level" error in Xcode. Why?
Here's the code I used to pass the test:
let movieDictionary = ["Spectre": ["cast": ["Daniel Craig", "Christoph Waltz", "LÊa Seydoux", "Ralph Fiennes", "Monica Bellucci", "Naomie Harris"]]]
var leadActor: String = ""
// Enter code below
if let movie = movieDictionary["Spectre"],
let cast = movie["cast"] {
leadActor = cast[0]
}
But in xcode the compiler gives a "Statements are not allowed at the top level" error for the line "if let movie = movieDictionary["Spectre"]," . Why?
1 Answer
Matthew Young
5,133 PointsAre you pasting this in a Swift file within an Xcode project? If so, then the error is related to you not placing the code within any classes or functions. Here's an excerpt from the Swift blog post titled, "Files and Initialization":
"However, top-level code is not allowed in most of your Swift source files. For clarity, any executable statement not written within a function body, within a class, or otherwise encapsulated is considered top-level. We have this rule because if top-level code were allowed in all your files, it would be hard to determine where to start the program."
I would recommend testing these code challenges within Swift Playgrounds as the top-level code rule doesn't apply there.
Stijn van Lieshout
3,646 PointsYes, I was checking it in the funfacts app. Thanks for clearing this up!
Matthew Young
5,133 PointsMatthew Young
5,133 Pointsmoved from Comment to Answer