Created
June 13, 2019 17:53
-
-
Save zaimramlan/0da3e36a9c7c33d98f082bfa96adb989 to your computer and use it in GitHub Desktop.
[PLAYGROUND] Reusable Dictionaryable Protocol
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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