完成和返回值

completion and returning value

我正在为这段代码苦苦挣扎。我正在尝试 return json 从 api link 获得的数据。我阅读了其他几个问题,但没有找到让它发挥作用的方法。所有的游乐场代码都在这里。提前致谢!

import UIKit
import PlaygroundSupport

PlaygroundPage.current.needsIndefiniteExecution = true

struct WebsiteDescription: Decodable {
    let ETH: Devise
}
struct Devise: Decodable {
    let EUR : Double
}

func refreshPrices(DeLaDevise nom: String, completion: @escaping ((Double) -> Double)) -> Void {

    guard let url = URL(string: "https://min-api.cryptocompare.com/data/pricemulti?fsyms=" + nom + "&tsyms=EUR") else { return }
    URLSession.shared.dataTask(with: url) { (data, reponse, error) in
        guard let data = data else { return }
        var prix: Double = 0.0
        print(data)
        do {
            let website = try JSONDecoder().decode(WebsiteDescription.self, from: data)
            prix = website.ETH.EUR
            completion(prix)
        } catch let jsonErr {
            print(jsonErr)
        }
        }.resume()
    }

   refreshPrices(DeLaDevise: "ETH") { prix in
            print(prix)
   }

差不多。

这似乎是自相矛盾的,但闭包确实不是return,它传递了一个参数。

报错信息给了你一个准确的线索:

Cannot convert value of type '()' to closure result type 'Double'

只需将 return 值更改为 Void()

func refreshPrices(DeLaDevise nom: String, completion: @escaping (Double) -> ()) -> Void {