Open vinhnx opened 6 years ago
We can use Decoder
's keyDecodingStrategy
for more fine grain control over decoding strategy.
For example, we want the compiler to automatically convert snake case from json response into our camel case model definition:
let data = { "some_value": 123 }.data(using: .utf8)
struct Foo: Decodable {
var someValue
}
do {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
// foo.someValue will be automatically converted from json snake case
let foo = try decoder.decode(Foo.self, from: data)
} catch (let decodingError) {
print(decodingError)
}
NOTE that using key coding strategy has "nominal performance cost"
- Note: Using a key decoding strategy has a nominal performance cost, as each string key has to be inspected for the
_
character. --- from KeyDecodingStrategy.convertFromSnakeCase header
Testing NetworkRequest
and User
model by faking/stubbing the process
Reference: http://hoangtran.me/ios/testing/2016/09/12/unit-test-network-layer-in-ios/
Check https://github.com/vinhnx/iOS-notes/issues/47 on how to build a generic Moya network request.
tl,dr: Check my sample repository on how to build a DIY network client and serializing into model using Codable, with just a few lines of code. Also a unit testing that network client with stub example.
Reference: