[SOLVED] Transferring individual data to the model (SwiftUI)

Issue

How to pass data to a Model, for example if I have a very large text, how to create a separate data structure which I will pass to Model() How to define Text1 and Text2 to pass it to Model()

code:

struct Model: Identifiable {
    let id = UUID()
    let image: String
    let text: String
}

extension Model {
    static func AllModel() -> [Model] {
        
        return [ Model(image: "1", text: Text1),
                 Model(image: "2", text: Text2) ]
    }
}

I showed more details in the image
enter image description here

How to define Text1 and Text2 to pass it to Model()
I’m new here

Solution

This looks like a very generic question; actually, there all several different ways to achieve what you want, depending on how your code is structured.

Let me give you 4 examples below.

Use a dictionary

let text: [String: String] = ["Text1": "Test1", "Text2": "Test2"]

// Usage
        return [ Model(image: "1", text: text["Text1"] ?? "Default value"),
                 Model(image: "2", text: text["Text2"] ?? "Default value") ]

Object with an array

    struct MyText {     // Do NOT use "Text", which is a system object
        static let text = ["Test1", "Test2"]   // Or var
    }

// Usage
        return [ Model(image: "1", text: MyText.text[0]),
                 Model(image: "2", text: MyText.text[1]) ]

Object with different constants (or variables)

    struct MyText {     // Do NOT use "Text", which is a system object
        static let text1 = "Test1"    // Or var
        static let text2 = "Test2"    // Or var
    }

// Usage
        return [ Model(image: "1", text: MyText.text1),
                 Model(image: "2", text: MyText.text2) ]

Object with different instances

    struct MyText {     // Do NOT use "Text", which is a system object
        let text: String    // Or var
        init(_ text: String) {
            self.text = text
        }
    }

// Usage
let text1 = MyText("Test1")
let text2 = MyText("Test2")

...

        return [ Model(image: "1", text: text1.text),
                 Model(image: "2", text: text2.text) ]

There are many other possible solutions, combining the one above in different ways, or using other methods.

Answered By – HunterLion

Answer Checked By – Robin (BugsFixing Admin)

Leave a Reply

Your email address will not be published.