Expression not allowed at top level

Is there anyone able to help me worth some Swift coding. I have not done any coding since I was at university over 40 years ago, where I was taught Fortran 77, ICL Assembler and a bit of machine code, and bizarrely BBC BASIC. The ICL computer filled a six story tower block, and the programs I developed were punched out on punch cards which we handed through a hatch to as technician and we came back a few days later to be told the program had failed at line 10!! my first job, I taught myself Kerningham and Ritchie C. Then I decided I hated coding and concentrated on hardware, networking, servers and systems and later own the internet. So I have not done any coding for5 around 40 years. Now that I have retired I have decided to develop an App to help me3 control my diabetes, so I am trying t5o learn Swift from an online tutorial, so I can’t ask the tutor what I have done wrong. Our second lesson is on functions, and I swear I have copied his code exactly as he had it, but it won’t run and gives the error message:

“Expressions are not allowed at the top level”

I am using an iMac 24-inch M1, running macOS Sonoma 14.2.1 and using Xcode 15.2 I am not sure what version of Swift it is, I assume it is the latest??

This the code ibn total:

import SwiftUI

@main
struct MyApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

var amount: Double = 120
var personCount = 2

func calculateATip(amount: Double) {
    let tip = amount * 10 / 100
    print(tip)
}

calculateATip(amount: 120)

It fails on the last line, what have I done wrong?

What you've done wrong (i mean not compliant with Swift compiler rules) is to call a func at the top level, not inside a func or a view.

When you call in a view, don't call direcly in the body, but ffor instance in a button action:

You should for instance call it in ContentView:

struct ContentView: View {

    var body: some View {
           Text("Hello, world!")
            Button {
                 calculateATip(amount: 120)
            } label: {
                Text("Calculate")
            }
    }
}

Thank you Claude,

I think I understand, but remember I am 40 years out of date.

I have used something called "Playground" and it seems to work there. I am not sure what "Playground" is maybe I need to watch more of the tutorial.

Expression not allowed at top level
 
 
Q