gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 01:27:03 24 4
gpt4 key购买 nike

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

一种解决方案是我将 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
}

这个函数应该被执行。

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

当我想初始化类时,我失败了。

CommandActions(action: doSomeAction(parameter1: "test"))

失败是:无法将“String”类型的值转换为预期的参数类型“(String) async throws -> String”

我尝试了不同的变体,但我不明白。目标是只在 SwiftUI 类中调用这样的东西:commandActions.action

最佳答案

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

public class CommandActions {
// MARK: Lifecycle

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

// MARK: Public

public let action: () async -> Void
}

初始化命令

public func getCommands() -> CommandActions {
CommandActions { [self] in
await myFunction()
}
}

函数

private func myFunction() async {
// do some stuff here
}

关于swift - 通过 SwiftUI 组件的参数传递异步函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69823101/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com