void 函数中出现意外的非 void 返回值。如何从函数返回变量?

时间:2021-06-09 02:09:28

标签: ios swift xcode

如何从函数返回双精度变量?

class Api {
    func getCoordinates(latitude: Bool) -> Double {
        if (latitude) {
            let url = URL(string: "https://waterservices.usgs.gov/nwis/iv/?format=json&indent=on&sites=08155200&parameterCd=00065&siteStatus=all")!
            URLSession.shared.dataTask(with: url) { data, _, _ in
                if let data = data {
                    let posts = try! JSONDecoder().decode(Post.self, from: data)
                    let lat = (posts.value?.timeSeries?.first?.sourceInfo?.geoLocation?.geogLocation?.latitude)
                    return lat
                }
            }
            print(5)
//            return 5
        } else {
            print(3)
            return 3
        }
    }
}

使用此代码返回:

Unexpected non-void return value in void function

我总是可以删除 return lat 但这会破坏目的。

1 个答案:

答案 0 :(得分:0)

这是一个关闭。 Async/await 即将推出,但与此同时,请记住 URLSession.shared.dataTask 是一个异步函数。这意味着完成处理程序/闭包将在稍后调用。

因此,您需要添加另一个完成处理程序,而不是 return

class Api {
                                        /// add completion handler
    func getCoordinates(latitude: Bool, completion: @escaping ((Double) -> Void)) {
        if (latitude) {
            let url = URL(string: "https://waterservices.usgs.gov/nwis/iv/?format=json&indent=on&sites=08155200&parameterCd=00065&siteStatus=all")!
            URLSession.shared.dataTask(with: url) { data, _, _ in
                if let data = data {
                    let posts = try! JSONDecoder().decode(Post.self, from: data)
                    let lat = (posts.value?.timeSeries?.first?.sourceInfo?.geoLocation?.geogLocation?.latitude)
                    completion(lat) /// similar to `return lat`
                }
            }
            print(5)
        } else {
            print(3)
            completion(3) /// similar to `return 3`
        }
    }
}

您的旧代码可能如下所示:

let returnedDouble = Api().getCoordinates(latitude: true)
print(returnedDouble)

现在,将其替换为:

Api().getCoordinates(latitude: true) { returnedDouble in
    print(returnedDouble)
}