通过 SwiftUI 组件的参数传递异步函数

kuz*_*zdu 7 asynchronous parameter-passing swift swiftui

我有一个带有按钮的 SwiftUI 组件,我想在不同的地方使用它。执行按钮时,应根据视图执行不同的操作。

一种解决方案是我将 ViewModel 传递给组件。但是,该解决方案无法很好地适应不同的 ViewModel。

我觉得使用回调的替代方法也不太好。因为组件的层次结构非常深。

我的想法是创建一个 CommandAction 类。但是,我在方法签名上失败了。

我的想法就是这堂课。

class CommandActions {
    // MARK: Lifecycle
    init(action: @escaping (( _ parameter1: String) async throws -> String)) {
        self.action = action
    }

    // MARK: Internal
    let action: ( _ parameter1: String) async throws -> String
}
Run Code Online (Sandbox Code Playgroud)

该函数应该被执行。

private func doSomeAction(parameter1: String) async throws -> String {
        await Task.sleep(seconds: 1)
        return "Some Result"
}
Run Code Online (Sandbox Code Playgroud)

当我想开始上课时,我失败了。

CommandActions(action: doSomeAction(parameter1: "test"))
Run Code Online (Sandbox Code Playgroud)

失败的是:Cannot convert value of type 'String' to expected argument type '(String) async throws -> String'

我尝试了不同的变体,但我不明白。目标是仅在 SwiftUI 类中调用类似的内容:commandActions.action

kuz*_*zdu 13

感谢您的评论,我找到了我正在寻找的解决方案。

public class CommandActions {
    // MARK: Lifecycle

    public init(action: @escaping () async -> Void) {
        self.action = action
    }

    // MARK: Public

    public let action: () async -> Void
}
Run Code Online (Sandbox Code Playgroud)

初始化命令

public func getCommands() -> CommandActions {
        CommandActions { [self] in
            await myFunction()
        }
    }
Run Code Online (Sandbox Code Playgroud)

和功能

private func myFunction() async {
  // do some stuff here
}
Run Code Online (Sandbox Code Playgroud)