Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 如何在do block内使用投掷?_Ios_Swift_Throw_Jsondecoder - Fatal编程技术网

Ios 如何在do block内使用投掷?

Ios 如何在do block内使用投掷?,ios,swift,throw,jsondecoder,Ios,Swift,Throw,Jsondecoder,如果可能的话,我想从do块内抛出错误 我有一个函数getWeatherBy,它被签名为抛出函数。我在应用程序中其他地方的代码取决于此。在这个函数的内部有一个JSONDecoder.decode,它抛出函数本身,在do块的内部有一个。然而,如果JSONDecoder有错误,我想从getWeatherBy抛出错误,但是由于抛出是在JSONDecoder内部发生的,所以它在那里被捕获 对不起,代码太乱了。我还是一个新手,任何关于如何使这段代码更好的想法都是非常受欢迎的 func getWeatherB

如果可能的话,我想从do块内抛出错误

我有一个函数getWeatherBy,它被签名为抛出函数。我在应用程序中其他地方的代码取决于此。在这个函数的内部有一个JSONDecoder.decode,它抛出函数本身,在do块的内部有一个。然而,如果JSONDecoder有错误,我想从getWeatherBy抛出错误,但是由于抛出是在JSONDecoder内部发生的,所以它在那里被捕获

对不起,代码太乱了。我还是一个新手,任何关于如何使这段代码更好的想法都是非常受欢迎的

func getWeatherBy(city: String, completion: ((WeatherRecord) -> ())?) throws {
        let trimmedCityName = (city as NSString).replacingOccurrences(of: " ", with: "+")
        
        let url = URL(string: "https://api.openweathermap.org/data/2.5/weather?q=\(trimmedCityName.lowercased())&appid=\(self.OpenWeatherAPIkey)&units=metric")
        guard url != nil else { return }
        print(url!)

        let networkTask: URLSessionDataTask = URLSession.shared.dataTask(with: url!) {
            (data, response, error) in
            guard let data = data else { return }
            
            do {
                let decoded = try JSONDecoder().decode(WeatherData.self, from: data)
                if (decoded.main != nil) {
                    if (decoded.coord?.lat != nil) {
                        DispatchQueue.main.async {
                            let record = WeatherRecord(temperature: Float(decoded.main!.temp), date: Date(), coordinates: CLLocationCoordinate2D(latitude: decoded.coord!.lat, longitude: decoded.coord!.lon), distance: 0.0)
                            
                            if completion != nil {
                                completion!(record)
                                
                            }
                        }
                    }
                } else {
                    throw serviceError.cityNotFound
                }
                
                if (decoded.message != nil) {
                    print("Message: \(decoded.message!)")
                    
                    DispatchQueue.main.async {
                        if (String(describing: decoded.message!).contains("Your account is temporary blocked") == true) {
                            
                        }
                        
                        if (decoded.message! != "Nothing to geocode") || String(describing: decoded.message!).contains("Your account is temporary blocked") != false {
                            
                        }
                    }
                }
            } catch DecodingError.keyNotFound(let key, let context) {
                Swift.print("Could not find key \(key) in JSON: \(context.debugDescription)")
            } catch DecodingError.valueNotFound(let type, let context) {
                Swift.print("Could not find type \(type) in JSON: \(context.debugDescription)")
            } catch DecodingError.typeMismatch(let type, let context) {
                Swift.print("Type mismatch for type \(type) in JSON: \(context.debugDescription) \(context)")
            } catch DecodingError.dataCorrupted(let context) {
                Swift.print("Data found to be corrupted in JSON: \(context.debugDescription)")
            } catch let error as NSError {
                NSLog("Error in read(from:ofType:) domain= \(error.domain), description= \(error.localizedDescription)")
            }
        }

最常见的方法是添加带有/不带有新错误的错误


您不能立即从异步方法抛出

抛出的JSONDecoder位于异步回调中-即,如果抛出,它将异步完成。同步
getWeatherBy
函数不能抛出相同的错误。您可以做的是将错误作为参数传递给完成闭包。查看作为传递成功值或错误的一种方法,我看到了!非常感谢!您可以从异步函数中抛出,但它会稍后出现。这是Objective-C。Swift签名与
->Void
相同:
()抛出->天气记录->Void
func getWeatherBy(city: String, completion: ((WeatherRecord? , Error?) -> ()))