Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zaimramlan/0da3e36a9c7c33d98f082bfa96adb989 to your computer and use it in GitHub Desktop.
Save zaimramlan/0da3e36a9c7c33d98f082bfa96adb989 to your computer and use it in GitHub Desktop.
[PLAYGROUND] Reusable Dictionaryable Protocol
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)")
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment