Sus*_*ggs 1 async-await swift swiftui
我试图理解为什么它Task{}
有效的原因,但是当我这样做时,VStack{}.task{}
我收到错误:
从“@Sendable () async throws -> ()”类型的抛出函数到非抛出函数类型“@Sendable () async -> Void”的转换无效
我试图让该fetchWeather()
函数在视图启动时运行,而无需用户点击按钮。(如果下面的方法是正确的方法)但是遇到了这个错误并且我真的很好奇这个错误背后的原因
下面是我的代码:
struct WeatherView: View {
var body: some View {
VStack{
Text("Hello, World!")
Button("Get Weather", action: {
// Works when I tap the button
// Task {
// try await fetchWeather()
// }
})
}
//*******Xcode error with invalid conversion*******
.task {
try await fetchWeather()
}
}
}
struct WeatherView_Previews: PreviewProvider {
static var previews: some View {
WeatherView( )
}
}
Run Code Online (Sandbox Code Playgroud)
功能:
func fetchWeather () async throws {
let URLString = "https://api.openweathermap.org/data/2.5/weather?appid=someAPIKeyshere&q=seattle"
let (data, response) = try await URLSession.shared.data(from: URL(string: URLString)!)
guard let httpResponse = response as? HTTPURLResponse,
httpResponse.statusCode == 200 else {
throw ResponseError.someError
}
let decodedResponse = try? JSONDecoder().decode(WeatherData.self, from: data)
print("This is in decodedResponse: \(decodedResponse)")
}
Run Code Online (Sandbox Code Playgroud)
提前致谢!
查看您收到的错误消息\xe2\x80\xa6
\n您的函数类型为:
\n@Sendable () async throws -> ()\n
Run Code Online (Sandbox Code Playgroud)\n而.task
修饰符期望\xe2\x80\xa6
@Sendable () async -> Void\n
Run Code Online (Sandbox Code Playgroud)\n区别在于throws
.
要解决这个问题,您需要处理函数抛出的错误,例如\xe2\x80\xa6
\n.task {\n do {\n try await fetchWeather()\n } catch {\n // handle error\n }\n}\n
Run Code Online (Sandbox Code Playgroud)\n您可以比较初始化程序Task
和.task
修饰符采用的参数:
Task.init
init(priority: TaskPriority? = nil, operation: @escaping @Sendable () async throws -> Success)\n
Run Code Online (Sandbox Code Playgroud)\n.task
修饰语
func task(priority: TaskPriority = .userInitiated, _ action: @escaping @Sendable () async -> Void) -> some View\n
Run Code Online (Sandbox Code Playgroud)\n
归档时间: |
|
查看次数: |
1343 次 |
最近记录: |