Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift CLI app 'main' attribute cannot be used in a module that contains top-level code

I am trying to call functions from EventKit in a simple command line tool app. However, some of the functions are async, which results in 'async' call in a function that does not support concurrency. I found this SO question but neither of the given solutions work.

Putting code inside Task {} never runs, and declaring a struct with a static func main() async function wont compile with the error 'main' attribute cannot be used in a module that contains top-level code. I am trying to run a single file test.swift with the following content.

import Foundation
import EventKit

@main
struct Test {
    static func main() async {
        var reminders = EKEventStore.init()
        
        print("run")
        
        if EKEventStore.authorizationStatus(for: EKEntityType.reminder) != EKAuthorizationStatus.authorized {
            do {
                var ok = try await reminders.requestAccess(to: EKEntityType.reminder)
                print(ok)
            } catch {
                print("error")
                return
            }
        }
        print("authroized")
    }
}
like image 229
unknownperson Avatar asked Sep 05 '25 17:09

unknownperson


2 Answers

At least for me, I had this issue when using @main in main.swift. I renamed main.swift to some random name and the error went away.

Edit: as others have mentioned, Apple states the following.

You can either have a main.swift file or a @main entrypoint, but not both

like image 125
MAH Avatar answered Sep 07 '25 12:09

MAH


This is a bug in Swift. Running with -parse-as-library as an argument for the compiler makes it work.

like image 23
unknownperson Avatar answered Sep 07 '25 13:09

unknownperson