Skip to content

Swift Macro, Parsing Sealed Class JSON Model on Server (ex. kotlin server)

Notifications You must be signed in to change notification settings

leedh2004/SealedMacro

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

17 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

SealedMacro

✨ Swift Macro, Parsing Sealed Class JSON Model. (ex. kotlin server's sealed class json)

At a Glance

JSON Response

{
  "_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 Swift Model

@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
  }
}

Decoding & Encoding logic is automatically implemented.

// 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)
}

Installation

Using Swift Package Manager:

import PackageDescription

let package = Package(
  name: "MyAwesomeApp",
  dependencies: [
    .package(url: "https://github.com/leedh2004/SealedMacro.git", from: "0.3.0")
  ]
)

License

SealedMacro is under MIT license. See the LICENSE file for more info.

About

Swift Macro, Parsing Sealed Class JSON Model on Server (ex. kotlin server)

Resources

Stars

Watchers

Forks

Packages

No packages published

Languages