Created
April 26, 2018 13:45
-
-
Save SixBe/c0ec47335aabfad00d0f190b87bf654b to your computer and use it in GitHub Desktop.
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 | |
@objc public protocol DataSourceProtocol: AnyObject { | |
@objc func runDataSourceRequest(_ dataSourceRequest: DataSourceRequest) -> AnyObject? | |
} | |
@objc public protocol DataSourceRequest { | |
var responseModel: AnyClass { get } | |
} | |
class DataSource: DataSourceProtocol { | |
@objc func runDataSourceRequest(_ dataSourceRequest: DataSourceRequest) -> AnyObject? { | |
guard let modelClass = dataSourceRequest.responseModel as? Decodable.Type else { | |
print("This is not working") | |
return nil | |
} | |
return self.runWithoutTemplate(responseModelClass: modelClass) | |
} | |
func runWithoutTemplate(responseModelClass: Decodable.Type) -> AnyObject? { | |
let data = """ | |
{ | |
"isTesting": true | |
} | |
""".data(using: .utf8)! | |
let decoder = JSONDecoder() | |
let model = try? decoder.decode(responseModelClass, from: data) | |
print("\(String(describing: model))") | |
return model as AnyObject | |
} | |
} | |
extension JSONDecoder { | |
struct DecodingHelper: Decodable { | |
private let decoder: Decoder | |
init(from decoder: Decoder) throws { | |
self.decoder = decoder | |
} | |
func decode(to type: Decodable.Type) throws -> Decodable { | |
let decodable = try type.init(from: decoder) | |
return decodable | |
} | |
} | |
func decode(_ type: Decodable.Type, from data: Data) throws -> Decodable { | |
let decodingHelper: DecodingHelper = try JSONDecoder().decode(DecodingHelper.self, from: data) | |
let decodable = try decodingHelper.decode(to: type) | |
return decodable | |
} | |
} | |
@objc class TestModel: NSObject, Decodable { | |
@objc var isTesting: Bool | |
private init(isTesting: Bool) { | |
self.isTesting = isTesting | |
} | |
} | |
@objc class TestDataSourceRequest: NSObject, DataSourceRequest { | |
@objc var responseModel: AnyClass { | |
return TestModel.self | |
} | |
} | |
let dataSource = DataSource() | |
let dataSourceRequest = TestDataSourceRequest() | |
let model = dataSource.runDataSourceRequest(dataSourceRequest) as? TestModel | |
model?.isTesting |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Quoting @SixBe: