Skip to content

Instantly share code, notes, and snippets.

@mihaelamj
Last active May 31, 2018 17:23
Show Gist options
  • Save mihaelamj/5e0b63b6718c07e2d728d74fe13ca91a to your computer and use it in GitHub Desktop.
Save mihaelamj/5e0b63b6718c07e2d728d74fe13ca91a to your computer and use it in GitHub Desktop.
Are you getting you collections for the backend in an unexpected way? Sometimes as an array and other times as dictionary? This gist tries to solve that.
extension String : CodingKey {
public var stringValue: String {
return self
}
public init?(stringValue: String) {
self.init(stringLiteral: stringValue)
}
public var intValue: Int? {
return nil
}
public init?(intValue: Int) {
return nil
}
}
//MARK: Decoder -
public func decodeModel<T>(from decoder: Decoder) throws -> T? where T: Decodable {
let object = try T(from: decoder)
return object
}
public func decodeArray<T>(type: [T].Type, from decoder: Decoder, key : String? = nil) throws -> [T]? where T: Decodable {
if let aKey = key {
let container = try decoder.container(keyedBy: String.self)
debugPrint(container.allKeys)
let array : [T] = try container.decode(type, forKey:aKey)
return array
}
let array : [T] = try [T].init(from: decoder)
return array
}
public func decodeDictionary<T>(type: [String : T].Type, from decoder: Decoder, key : String? = nil) throws -> [T]? where T: Decodable {
if let aKey = key {
let container = try decoder.container(keyedBy: String.self)
debugPrint(container.allKeys)
let dict = try container.decode(type, forKey:aKey)
var allItems : [T] = [T]()
for (_, item) in dict {
allItems.append(item)
}
return allItems
}
let dict : [String : T] = try [String : T].init(from: decoder)
var alItems : [T] = [T]()
for (_, item) in dict {
alItems.append(item)
}
return alItems
}
public func decodeCollection<T>(type: T.Type, from decoder: Decoder, key : String? = nil) throws -> [T]? where T: Decodable {
var alItems : [T]? = nil
//first try with array
do {
try alItems = decodeArray(type: [T].self, from: decoder, key: key)
print(alItems ?? "no items")
} catch {
debugPrint(error)
}
//if we got no items
guard alItems != nil else {
//try with dictionary
do {
try alItems = decodeDictionary(type: [String : T].self, from: decoder, key: key)
print(alItems ?? "no items")
} catch {
debugPrint(error)
}
return alItems
}
return alItems
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment