ios - 我如何从这个输出中获取用户值(value)

标签 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 中获取结果呢?

感谢您的帮助

最佳答案

在花了更多时间并了解了我正在处理的内容之后:) 我想出了我应该如何获取用户对象。

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

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

Value 结构如下:

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

希望这对其他人有帮助。

关于ios - 我如何从这个输出中获取用户值(value),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50001613/

相关文章:

自定义键盘扩展中的 iOS8 UIImagePickerController

iOS - 在不使用 UIBarButtonItem 的委托(delegate)方法的情况下显示/隐藏 UISplitViewController

iphone - 除了自定义 URL 方案之外,还有其他方法可以调用应用内电话吗?

json - 带有嵌套 json 作为字符串的 Swift Codable

ios - 整数文字存储到 'Int'错误时溢出

swift4 - 通过 Interface Builder 使 NSTableView 列可排序

swift - FireStore Swift 4 : How to get total count of all the documents inside a collection, 并获取每个文件的详细信息?

ios - Google Vision - OCR - 请求必须指定图像和特征

swift - 在 Swift 中听标准输入

ios - @IBInspectable NSLayoutConstraint 不工作 Xcode 8.2.1 (8C1002)