Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import UIKit
- var json = """
- {
- "type": "int",
- "value": 1
- }
- """
- struct MyString: Codable {
- let value: String
- enum keys: CodingKey {
- case value
- }
- }
- struct MyInt: Codable {
- let value: Int
- }
- struct TypeContainer: Decodable {
- let type: SupportedType
- enum SupportedType: String, Codable {
- case string
- case int
- }
- }
- do {
- let typeContainer = try JSONDecoder().decode(TypeContainer.self, from: json.data(using: .utf8)!)
- switch typeContainer.type {
- case .string:
- let string = try JSONDecoder().decode(MyString.self, from: json.data(using: .utf8)!)
- print("string value: \(string.value)")
- case .int:
- let int = try JSONDecoder().decode(MyInt.self, from: json.data(using: .utf8)!)
- print("int value: \(int.value)")
- }
- } catch {
- print(error)
- }
Advertisement
Add Comment
Please, Sign In to add comment