user6539552
user6539552

Reputation: 1451

Global variable in Swiftui

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?

Upvotes: 0

Views: 1662

Answers (1)

MilesStanfield
MilesStanfield

Reputation: 4639

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())
  }
}

Upvotes: 1

Related Questions