Skip to content

Instantly share code, notes, and snippets.

{
"body":[
{
"type":"string",
"content":"Lorem ipsum text"
},
{
"type":"int",
"content":10
}
struct Content: Decodable {
var body: [Body]
}
struct Body: Decodable {
var type: String
var content: ???
}
// Enum with type as type of the content
// Assciated value will hold the actual content data
enum BodyContent {
case number(Int)
case text(String)
case unsupported
}
// Now we can represent our Models as
struct Content: Decodable {
// json is a variable holding a JSON Data value
let myStruct = try JSONDecoder().decode(Content.self, from: json) // decoding our data
myStruct.body.forEach { (value: BodyContent) in
switch value {
case .number(let number):
print("Data for type: number is Data: \(number)")
case .text(let string):
print("Data for type: string is Data: \(string)")
case .unsupported:
print("Type not supported")
struct Content: Decodable {
var body: [Body]
}
protocol BodyContent: Decodable {
func getContent<T: Decodable>() -> T?
}
struct Body: Decodable {
var type: String
let myStruct = try JSONDecoder().decode(Content.self, from: json) // decoding our data
myStruct.body.forEach { bodyContent in
let value: String? = bodyContent.content?.getContent()
let intValue: Int? = bodyContent.content?.getContent()
let finalValue = value ?? intValue.map(String.init) ?? "NA"
print("Data for type: \(bodyContent.type) is Data: \(finalValue)")
}
import SwiftUI
import PlaygroundSupport
struct ContainerView: View {
var body: some View {
VStack() {
Text ("Hello World")
.font(.title)
.color(.blue)
@available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *)
public protocol View : _View {
/// The type of view representing the body of this view.
///
/// When you create a custom view, Swift infers this type from your
/// implementation of the required `body` property.
associatedtype Body : View
/// Declares the content and behavior of this view.
public init(alignment: HorizontalAlignment = .center,
spacing: Length? = nil,
content: () -> Content)
// Original source code:
@TupleBuilder
func build() -> (String, String, Int) {
"a"
"b"
1
}
// This code is interpreted exactly as if it were this code:
func build() -> (String, String, Int) {