如何在 swiftui 的文本视图中使用来自 actor 的异步值
我正在使用 xcode 13.3 beta 3 并尝试修改我的应用程序以使用 actor。由于我的所有变量现在都位于参与者中,因此无法直接访问它们,因此如何在文本视图中使用这些异步值?我从上一篇文章中找到了以下链接的一个可能的解决方案: 如何在 Swift 5.5 中将 async/await 与 SwiftUI 一起使用?。这是我能找到在文本视图中使用异步值的唯一方法。这种方法的问题是,通过使用 @State 变量,我需要将这些值传递给......我不能这样做......有什么想法吗?
struct Forecast: View {
@EnvironmentObject var ws: Webservice
@State var forecast1tempMin = 0
....
VStack {
Text("\(forecast1tempMin)")
.foregroundColor(.white)
.task {
forecast1tempMin = await ws.forecastActor.getForecast1TempMin()
}
actor Forecast_Actor {
@Published var forecast1_tempmin = 0
func setForecast1TempMin(val: Int) async {
forecast1_tempmin = val
}
func getForecast1TempMin() async -> Int {
return forecast1_tempmin
}
struct ContentView: View {
@State var text = "Loading"
// Async function
func asyncGetText() async -> String {
try? await Task.sleep(nanoseconds: 3 * NSEC_PER_SEC)
return "My text"
}
var body: some View {
Text(text)
.task {
text = await asyncGetText()
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
I am using xcode 13.3 beta 3 and trying to modify my app to use actors. Since all of my variables are now in an actor(s) so they cannot be accessed directly, how do I use these async values in a Text View? I found one possible solution from the last post for the following link: How can I use async/await with SwiftUI in Swift 5.5?. This was the only way I could find to use an async value in a Text View. The problem with this approach is that by using @State variable, I am required to pass those values in....which I can't do...Any ideas?
struct Forecast: View {
@EnvironmentObject var ws: Webservice
@State var forecast1tempMin = 0
....
VStack {
Text("\(forecast1tempMin)")
.foregroundColor(.white)
.task {
forecast1tempMin = await ws.forecastActor.getForecast1TempMin()
}
actor Forecast_Actor {
@Published var forecast1_tempmin = 0
func setForecast1TempMin(val: Int) async {
forecast1_tempmin = val
}
func getForecast1TempMin() async -> Int {
return forecast1_tempmin
}
struct ContentView: View {
@State var text = "Loading"
// Async function
func asyncGetText() async -> String {
try? await Task.sleep(nanoseconds: 3 * NSEC_PER_SEC)
return "My text"
}
var body: some View {
Text(text)
.task {
text = await asyncGetText()
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如何执行此操作的原始示例来自 stackoverflow 上的 @malhal。我做了一些改变以满足我的需要。最初的问题是如何将异步调用中的异步值传递到 swiftui Text() 视图中。我试图传入一个 Int 并需要将其变成一个 String。
以下解决了我的问题。谢谢!
The original example of how to do this came from @malhal here on stackoverflow. I changed things around a bit to suit my needs. The original issue was how to pass into a swiftui Text() view an async value from an async call. I was trying to pass in an Int and needed to make it a String.
The following solved my problem. Thanks!