Elegant Codable implementation using Swift Macro
The way of implementing a custom decoder at compile time has been changed to using Swift Macro (currently only supported by Swift Package). This has the following benefits over a custom decoder:
All of these can be solved with HappyCodable.
Apply HappyCodable
to your struct/class/enum:
import HappyCodable
extension HappyEncodable {
static var decodeHelper: DecodeHelper {
.init()
}
}
extension HappyDecodable {
static var encodeHelper: EncodeHelper {
.init()
}
}
@HappyCodable
struct Person: HappyCodable {
var name: String = "abc"
@AlterCodingKeys("🆔")
var id: String = "abc"
@AlterCodingKeys("secret_number", "age")
var age: Int = 18
@DataStrategy(decode: .deferredToData, encode: .deferredToData)
var data_deferredToData: Data = Data()
@DateStrategy(decode: .secondsSince1970, encode: .secondsSince1970)
var date_secondsSince1970: Date = Date(timeIntervalSince1970: 1234)
@AlterCodingKeys("data1")
@ElementNullable
var data: [String] = []
@Uncoding
var secret_number: String = "3.1415"
init() { }
}
I used HandyJSON before, but because HandyJSON is based on operating on Swift's underlying data structures, it has had problems several times after Swift version updates due to changes in data structures. Since I don't want to manually parse models, it prompted me to write this library. Having enough test cases with HappyCodable is safer than manual implementation.
Some people might say that updating HandyJSON is enough, but you can't guarantee that Swift won't update the underlying data structure in the future, causing HandyJSON to die. Nor can you guarantee that your app suddenly stops development and your users can't use it after updating the system.
To migrate to HappyCodable, HappyCodable's API is largely based on HandyJSON.
Yes.
To be continued...
link |
Stars: 46 |
Last commit: 26 weeks ago |
Swiftpack is being maintained by Petr Pavlik | @ptrpavlik | @swiftpackco | API | Analytics