✨ Swift Macro, Parsing Sealed Class JSON Model. (ex. kotlin server's sealed class json)
{
"_type": "IMAGE",
"imageURL": "https://github.com/images",
"imageName": "source"
}
{
"_type": "LOTTIE",
"lottieURL": "https://github.com/lotties"
}
{
"_type": "ICON_TYPE",
"iconURL": "https://github.com/icons"
}
@Sealed(typeKey: "_type", typeParseRule: .upperSnakeCase)
enum ImageSource: Codable {
case image(Image)
case lottie(Lottie)
case iconType(Icon)
}
extension ImageSource {
struct Image: Codable {
var imageURL: String
var imageName: String
}
struct Lottie: Codable {
var lottieURL: String
}
struct Icon: Codable {
var iconURL: String
}
}
// MARK: Test Decode & Encode
func testSealedDecoingAndEncoding() {
let json = """
{
"_type": "ICON_TYPE",
"iconURL": "https://github.com/icons"
}
"""
let jsonData = Data(json.utf8)
let imageSource = try? decoder.decode(ImageSource.self, from: jsonData)
XCTAssertTrue(imageSource != nil)
let encodedData = try? encoder.encode(imageSource)
XCTAssertTrue(encodedData != nil)
let reDecodedImageSource = try? decoder.decode(ImageSource.self, from: encodedData!)
XCTAssertTrue(reDecodedImageSource != nil)
}
Using Swift Package Manager:
import PackageDescription
let package = Package(
name: "MyAwesomeApp",
dependencies: [
.package(url: "https://github.com/leedh2004/SealedMacro.git", from: "0.3.0")
]
)
SealedMacro is under MIT license. See the LICENSE file for more info.