You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift Playground出现“Expressions are not allowed at the top level”错误的解决方案咨询

Got it, let's break this down for you.

The reason you can call functions at the top level in Swift Playgrounds but not in a real project is because Playgrounds are built as an interactive sandbox—they let you run code snippets directly for quick testing and experimentation. But in regular Swift projects (like iOS/macOS apps, command-line tools, or frameworks), the top level of a .swift file is reserved only for declarations (variables, functions, classes, structs, etc.), not for executing expressions or function calls. That’s exactly why you’re hitting the "Expressions are not allowed at the top level" error.

Here are the most common fixes, tailored to different project types:

1. For Command-Line Tool Projects

Command-line tools rely on a main() function as their execution entry point. Wrap your function calls inside this entry point:

❌ Bad (Top-Level Call)

print("Hello from CLI")
func myCustomFunction() {
    print("Running my function")
}
myCustomFunction() // Error: Expression not allowed at top level

✅ Fixed (Use @main or main() Function)

func myCustomFunction() {
    print("Running my function")
}

// Modern approach with @main
@main
struct MyCLITool {
    static func main() {
        print("Hello from CLI")
        myCustomFunction() // Safe to call here
    }
}

// Or the older, explicit main function (still works)
// func main() {
//     print("Hello from CLI")
//     myCustomFunction()
// }

2. For iOS/macOS App Projects

Apps have defined lifecycles—you need to trigger your function calls at the right lifecycle moment:

Option A: UIKit with AppDelegate

func myCustomFunction() {
    print("Running my function")
}

@main
class AppDelegate: UIResponder, UIApplicationDelegate {
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Call your function when the app finishes launching
        myCustomFunction()
        return true
    }
}

Option B: SwiftUI App

func myCustomFunction() {
    print("Running my function")
}

@main
struct MySwiftUIApp: App {
    init() {
        // Call during app initialization
        myCustomFunction()
    }

    var body: some Scene {
        WindowGroup {
            ContentView()
                .onAppear {
                    // Or call when the main view appears
                    myCustomFunction()
                }
        }
    }
}

3. For Any Project: Wrap in a Lifecycle Method

If you’re working with a view controller, view model, or any component with a lifecycle, call your function inside its appropriate method:

func myCustomFunction() {
    print("Running my function")
}

class MyViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        // Call when the view finishes loading
        myCustomFunction()
    }
}

Core Takeaway

In real Swift projects, top-level code is only for defining things (functions, types, constants), not for running things. All execution logic needs to live inside a function or method that gets triggered by your project’s entry point or lifecycle events.

内容的提问来源于stack exchange,提问作者Farid Rzayev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 22:07:50