Swift CLI 应用程序“main”属性不能在包含顶级代码的模块中使用

问题描述 投票:0回答:3

我正在尝试在一个简单的命令行工具应用程序中调用 EventKit 中的函数。然而,有些函数是

async
,导致
'async' call in a function that does not support concurrency
。我发现了这个问题,但是给定的解决方案都不起作用。

将代码放入

Task {}
中永远不会运行,并且使用
static func main() async
函数声明结构体不会编译并出现错误
'main' attribute cannot be used in a module that contains top-level code
。我正在尝试运行包含以下内容的单个文件
test.swift

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")
    }
}
swift async-await
3个回答
36
投票

至少对我来说,在 main.swift 中使用

@main
时遇到了这个问题。我将 main.swift 重命名为一些随机名称,错误就消失了。


6
投票

这是 Swift 中的一个 bug 。使用

-parse-as-library
作为编译器的参数运行使其可以工作。


0
投票

确保进行干净的构建(删除任何旧的输出)。我删除了“main.swift”并将其替换为我自己的 Swift 文件,然后遇到了这个问题。

清理构建目录对我来说很有效。

© www.soinside.com 2019 - 2024. All rights reserved.