Task{} 有效,但 .task{} 抛出异常 抛出类型错误的函数导致无效转换?

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)

提前致谢!

Ash*_*lls 6

查看您收到的错误消息\xe2\x80\xa6

\n

您的函数类型为:

\n
@Sendable () async throws -> ()\n
Run Code Online (Sandbox Code Playgroud)\n

.task修饰符期望\xe2\x80\xa6

\n
@Sendable () async -> Void\n
Run Code Online (Sandbox Code Playgroud)\n

区别在于throws.

\n

要解决这个问题,您需要处理函数抛出的错误,例如\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修饰符采用的参数:

\n

Task.init

\n
init(priority: TaskPriority? = nil, operation: @escaping @Sendable () async throws -> Success)\n
Run Code Online (Sandbox Code Playgroud)\n

.task修饰语

\n
func task(priority: TaskPriority = .userInitiated, _ action: @escaping @Sendable () async -> Void) -> some View\n
Run Code Online (Sandbox Code Playgroud)\n