Expressions are not allowed at the top level

HI

I haven't coded in a long time and I don't know how to use CodeX and now I can't move on from here, I don't know how to put the code in the right place in the code. :(

import SwiftUI

struct ContentView: View {
    var body: some View {
        VStack {
            Image(systemName: "globe")
                .imageScale(.large)
                .foregroundStyle(.tint)
            Text("Hello, world!")
        }
        .padding()
    }
}

#Preview {
    ContentView()

}
let range01INT1 = 100000 ... 199999
print("Range:",range01INT1,"Number of numbers", range01INT1.count)

Print command give me a error

let range01INT1 = 100000 ... 199999
print("Range:",range01INT1,"Number of numbers", range01INT1.count)

Expressions are not allowed at the top level

I know it's a stupid question, but I just can't get started.

You can't have executable code at the top level, as it's not clear when that code is executed.

Remove those lines, or move them into a function that can be called.

func printRange() {
    let range01INT1 = 100000 ... 199999
    print("Range:",range01INT1,"Number of numbers", range01INT1.count)
}

Hi, HulaBalooFl –

The other code in your sample indicates you've set up a new project using SwiftUI, which is a modern app centred around a graphical user interface. In that situation, the system looks for an entry point which is a struct conforming to App adorned with @main with the intent of setting up the app's interface, and then calls code within those types at appropriate times. In other words, it doesn't really run the lines of a program "top to bottom" like a traditional coder might expect.

If you're just trying to get to know the Swift language and run a sequence of lines in order with a printable output, you might want to start by choosing "New > Playground" and picking the "Blank" template, which just lets you edit and run code without building an app at all. Or perhaps, choose "New > Project" and then pick the "Command Line Tool" template, which lets you build an app without a graphical interface.

An easy solution is to put this code in onAppear:

struct ContentView: View {

    var body: some View {
        VStack {
            Image(systemName: "globe")
                .imageScale(.large)
                .foregroundStyle(.tint)
            Text("Hello, world!")
        }
        .padding()
        .onAppear() {
            let range01INT1 = 100000 ... 199999
            print("Range:",range01INT1,"Number of numbers", range01INT1.count)
        }
    }
}


And get:

Range: 100000...199999 Number of numbers 100000

Note it's Xcode, not CodeX

Expressions are not allowed at the top level
 
 
Q