-4

https://coinpaprika.github.io/coinpaprika-api-swift-client/index.html

func gettingFunction(name: String){
    Coinpaprika.API.coins().perform { (response) in
      switch response {
      case .success(let coins):

                return coins[0].id // i want return this value            

        case .failure(let error):
        print(error)
        // Failure reason as error
      }

    }

}
Jacob9812
  • 11
  • 2
  • 5
    Please look up “how to return value from asynchronous function” – this has been asked and answered many times already. – Martin R Jun 03 '20 at 07:19
  • Read here about callbacks: https://stackoverflow.com/questions/61429090/swift-variable-declared-outside-closure-is-updated-inside-closure-but-when-acces/61429216#61429216 – Deitsch Jun 03 '20 at 07:40

1 Answers1

2

It is an async call so you can use completion to do this. And you can pass Result type in completion with values

func gettingFunction(name: String, _ completion: @escaping (Result<Int, Error>) -> Void {
    Coinpaprika.API.coins().perform { response in
        switch response {
        case .success(let coins):

            completion(.success(coins[0].id))            

        case .failure(let error):
            print(error)
            completion(.failure(error))
      }

    }
}

Usage

gettingFunction(name: "asd") { result in
    switch result {
    case .success(let id):
        print("ID is:", id)
    case .failure(let error):
        print("Error is:", error)
    }
}

If you want to use the value in another function. You should call this function in .success case because we have the ID value in this case.

gettingFunction(name: "asd") { result in
    switch result {
    case .success(let id):
        print("ID is:", id)
        anotherFunction(id: id)

    case .failure(let error):
        print("Error is:", error)
    }
}
emrcftci
  • 3,355
  • 3
  • 21
  • 35
  • THANKS MAN, but what if i want return this value to another function? for example function(id: gettingFunction(name: "asd")) – Jacob9812 Jun 03 '20 at 07:32