Skip to content

Instantly share code, notes, and snippets.

@HereOrCode
Last active October 22, 2021 05:03
Show Gist options
  • Save HereOrCode/c09d7caa3f7dfcc52adf6359de1134e3 to your computer and use it in GitHub Desktop.
Save HereOrCode/c09d7caa3f7dfcc52adf6359de1134e3 to your computer and use it in GitHub Desktop.
Swift: Codable Nested Data
import UIKit
import SwiftPrettyPrint
/*
* SwiftPrettyPrint
* https://github.com/YusukeHosonuma/SwiftPrettyPrint
*/
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
test()
}
func test() {
// MARK: - Command
struct Command: Codable {
let name: String
let command: String?
let children: [Command]?
}
typealias Commands = [Command]
let data = """
[
{
"name": "google",
"command": "search webpage"
},
{
"name": "apple",
"children": [
{
"name": "iOS",
"children": [
{
"name": "iPhone",
"command": "search iPhone"
},
{
"name": "iPad",
"children": [
{
"name": "iPad1",
"command": "search iPad1"
},
{
"name": "iPad2",
"command": "search iPad2"
}
]
},
{
"name": "iWatch",
"command": "search iWatch"
}
]
}
]
},
{
"name": "microsoft",
"command": "search microsoft"
}
]
""".data(using: .utf8)!
let result = try! JSONDecoder().decode(Commands.self, from: data)
Pretty.prettyPrint(result)
}
}
/**
[
Command(
name: "google",
command: "search webpage",
children: nil
),
Command(
name: "apple",
command: nil,
children: [
Command(
name: "iOS",
command: nil,
children: [
Command(
name: "iPhone",
command: "search iPhone",
children: nil
),
Command(
name: "iPad",
command: nil,
children: [
Command(
name: "iPad1",
command: "search iPad1",
children: nil
),
Command(
name: "iPad2",
command: "search iPad2",
children: nil
)
]
),
Command(
name: "iWatch",
command: "search iWatch",
children: nil
)
]
)
]
),
Command(
name: "microsoft",
command: "search microsoft",
children: nil
)
]
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment