Skip to content

Instantly share code, notes, and snippets.

Revisions

  1. zaimramlan created this gist Jun 13, 2019.
    42 changes: 42 additions & 0 deletions playground_reusable_dictionaryable_protocol.swift
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,42 @@
    import Foundation

    protocol Dictionaryable {
    var keys: [String] { get }
    var values: [Any] { get }
    }

    extension Dictionaryable where Self: Codable {
    func toDictionary() -> Dictionary<String, AnyObject> {
    var dictionary = Dictionary<String, AnyObject>()

    for i in 0..<keys.endIndex {
    dictionary[keys[i]] = values[i] as AnyObject
    }

    return dictionary
    }
    }

    struct ResponseModel: Codable, Dictionaryable {
    var buy: String
    var sell: String

    enum CodingKeys: String, CodingKey, CaseIterable {
    case buy, sell
    }

    var keys: [String] { return CodingKeys.allCases.map({ $0.rawValue }) }
    var values: [Any] { return [buy, sell] }
    }

    func callApi(parameter1: Int, completion: ((ResponseModel) -> Void)) {
    var model = ResponseModel.init(buy: "0.99", sell: "1.99")
    print("Dictionaried: \(model.toDictionary())")
    completion(model)
    }

    callApi(parameter1: 0, completion: {
    response in
    print("BUY: \(response.buy)")
    print("SELL: \(response.sell)")
    })