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 Swift 2.0 Enumerations and Optionals Introduction to Optionals Optional Binding

Stijn van Lieshout
Stijn van Lieshout
3,646 Points

Code 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?

Matthew Young
Matthew Young
5,133 Points

moved from Comment to Answer

1 Answer

Matthew Young
Matthew Young
5,133 Points

Are 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.

Source: Swift Blog - Files and Initialization

Stijn van Lieshout
Stijn van Lieshout
3,646 Points

Yes, I was checking it in the funfacts app. Thanks for clearing this up!