Learn Courses My Dashboard

Calling an array from another file

Ive tried many times but nothing is working. I copied some code into my project that uses a hard-coded array. However, I want to use an array that I already have that is imported with a json file. Not sure if I call the class that is in my model or the class that is in my viewmodel that parses the json dated. I can’t get it to work either way. Any suggestions as to what i’m doing wrong?

Can you show your code from the file you want to use it in, and the one that it exists in?

You should be passing the data from one to another

This is the code with the hard-coded array. I want to assign a different array to originalItems.

import SwiftUI

class ContentViewModel: ObservableObject {

@Published var originalItems =

[“well-nurished”, “Agitated”, “equal”, “thin”, “ones”, “the”, “misfits”, “the”, “rebels”, “the”, “troublemakers”, “the”, “round”, “pegs”, “in”, “the”, “square”, “holes”, “the”, “ones”, “who”, “see”, “things”, “differently”, “they’re”, “not”, “fond”, “of”, “rules”, “You”, “can”, “quote”, “them”, “disagree”, “with”, “them”, “glorify”, “or”, “vilify”, “them”, “but”, “the”, “only”, “thing”, “you”, “can’t”, “do”, “is”, “ignore”, “them”, “because”, “they”, “change”, “things”, “they”, “push”, “the”, “human”, “race”, “forward”, “and”, “while”, “some”, “may”, “see”, “them”, “as”, “the”, “crazy”, “ones”, “we”, “see”, “genius”, “because”, “the”, “ones”, “who”, “are”, “crazy”, “enough”, “to”, “think”, “that”, “they”, “can”, “change”, “the”, “world”, “are”, “the”, “ones”, “who”, “do”]

@Published var spacing: CGFloat = 8

@Published var padding: CGFloat = 8

@Published var wordCount: Int = 75

@Published var alignmentIndex = 0

var words: [String] {

Array(originalItems.prefix(wordCount))

}

let alignments: [HorizontalAlignment] = [.leading, .center, .trailing]

var alignment: HorizontalAlignment {

alignments[alignmentIndex]

}

}

struct ContentView: View {

@StateObject var model = ContentViewModel()

This is the array that I want to use in the above code in another file. I want to use the array negPE instead of originalItems.

import Foundation

class Pizza: Identifiable, Decodable, ObservableObject {

// The id property is for the Identifiable protocol which we need to display these instances in a SwiftUI List
var id:UUID?

// These properties map to the properties in the JSON file
var name:String
var toppings:[String]
var negPE:[String]
var image:String

}

I also have my view model where I parse my json data:

import Foundation

class PizzaModel: ObservableObject {

@Published var pizzas = [Pizza]()

init() {
    
    // Find the path to the JSON file in our bundle
    let pathString = Bundle.main.path(forResource: "pizzas", ofType: "json")
    
    if pathString != nil {
        
        // Create a URL object with the string path to our local JSON file
        let url = URL(fileURLWithPath: pathString!)
        
        do {

etc…

Thanks, Todd