ANeme
ANeme

Reputation: 771

How can i get the user value from this output

I really can't find a way to get the user value from the below output

If I print the result directly I get

(TotersAPIFrameWork.Result<TotersAPIFrameWork.DataContainer<TotersAPIFrameWork.User>>) $R5 = success {
  success = {
    user = {
      id = 200
      first_name = "yara"
      last_name = "Padberg"
      email = "[email protected]"
      phone_number = "+9999"
      type = "client"
      account_type = "email"
      sm_user_id = nil
      sm_access_token = nil
      picture = ""
      deleted_at = nil
      created_at = "2018-04-04 14:33:29"
      updated_at = "2018-04-24 11:15:45"
      rating = "5"
      rating_count = 1
      regid = ""
      platform = "ios"
      is_agora = nil
      currency_id = 1
      is_verified = true
      promo_code_id = nil
      referral_promo_code_id = nil
      op_city_id = 1
      is_daas = false
      token = ""
      retailer_info = nil
    }
  }
}

I tried to convert directly to user like below

p result as? User 

it is returning nil, so how should i get the result from the DataContainer?

Thanks for your help

Upvotes: 1

Views: 92

Answers (1)

ANeme
ANeme

Reputation: 771

After spending more time and understanding what i'm dealing with :) i figured out how should i get the user object.

First of all the Result that i'm using is an enum and my callback is returning Result so below was the solution:

let login =  PostLogin.init(email: "[email protected]", password: "pass")
let client = APIClient(publicKey: "", privateKey:"")

 client.send(login) { (result) in
    switch result {
        case .success(let value):
            print(value)
        case .failure(let error):
            print(error)
    }
  }

The result is an enum:

import Foundation

public enum Result<Value> {
 case success(Value)
 case failure(Error)
}

public typealias ResultCallback<Value> = (Result<Value>) -> Void

The Value struct is below:

import Foundation

/// All successful responses return this, and contains all
/// the metainformation about the returned chunk.
public struct DataContainer<T: Decodable>: Decodable {

public var user:T?

public init(from decoder: Decoder) throws {

    let container = try decoder.container(keyedBy: UserResponseKeys.self)
    if let u = try container.decodeIfPresent(T.self, forKey: .user) 
    {
        self.user = u
    }
  }
}    

now i can get user like this:

let user = value.user

Hope this will help others.

Upvotes: 2

Related Questions