0
votes

I have a enum that defines the language index. I put this enum in a file named Language.swift

enum Language: Int {
    case en
    case zh_hant    
}

I have tried to declare a global variable that stores the current language.

final class ModelData: ObservableObject {
    @Published var currentLanguage: Language = Language.zh_hant
    @Published var globalString: [String] = load("strings.json")
}

However, when I tried to access that, I have the following error:

struct HomeView: View {

    @EnvironmentObject var modelData: ModelData
    
    var body: some View {
        Text("\(modelData.currentLanguage.rawValue)") // error, see the screen capture
        Text("\(modelData.globalString.count)") // no problem
    }
}

enter image description here

Yet, I used the same way to access the array, there is no problem.

The above error can be resolved by moving enum Language to be in the same file as class ModelData.

Yet, another problem was then identified.

I tried to do this in my code:

var languageIndex: Int {
        modelData.currentLanguage.rawValue
    }
var body: some View {
    Text("\(modelData.globalString[languageIndex])") // preview cause "updating took more than 5 seconds]
}

My global String like this ["Hello", "你好"]

The problem appears in the Canvas view on preview the UI. Yet, it seems to work fine under simulator. Any idea?

1
No error with Xcode 12.1 with just copy/pasted code. Maybe you have conflict with some other code in your project. - Asperi
I put the enum Language in a file called Language.swift, and hence caused the error. I cannot put them in another file that is different from the class ModelData? - user6539552

1 Answers

1
votes

The problem appears in the Canvas view on preview the UI. Yet, it seems to work fine under simulator.

You have to set the environment object in the preview

struct HomeView_Previews: PreviewProvider {
  static var previews: some View {
    HomeView()
      .environmentObject(ModelData())
  }
}