如何从此输出中获取用户值

时间:2018-04-24 12:23:52

标签: ios swift4

我真的找不到从下面输出中获取用户价值的方法

如果我直接打印结果,我会

(TotersAPIFrameWork.Result<TotersAPIFrameWork.DataContainer<TotersAPIFrameWork.User>>) $R5 = success {
  success = {
    user = {
      id = 200
      first_name = "yara"
      last_name = "Padberg"
      email = "client@client.com"
      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
    }
  }
}

我尝试直接转换为下面的用户

p result as? User 

它返回nil,那么我应该如何从DataContainer获得结果?

感谢您的帮助

1 个答案:

答案 0 :(得分:1)

在花了更多时间并了解我正在处理的事情之后:)我想出了如何获得用户对象。

首先,我使用的结果是一个枚举,我的回调正在返回结果,所以下面是解决方案:

let login =  PostLogin.init(email: "client@client.com", 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)
    }
  }

结果是枚举:

import Foundation

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

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

价值结构如下:

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
    }
  }
}    

现在我可以得到这样的用户:

let user = value.user

希望这会有所帮助。