I have an array that I want to change based on another variable, so that different things are displayed based on that variable's value.
In the below example, the variable that changes is "scores", and I want to display a different message list depending on what that value of "scores" is.
In the below example, I call a function and pass it "scores", it correctly returns a structure "Messages". All that works fine.
The problem occurs when "Messages" has an array size that is less than the previous value of Messages. i.e., if scores = 1, then the code runs fine, but if scores = 2, then "Messages.message[section]" crashes because the index is out of range. It therefore seems that the way my code works is that it just overwrites part of the "Messages" array, rather than recreates it. How do I solve that?
Many thanks!
Example code (simplified slightly for display purposes):
class MessageGetter: ObservableObject {
@Published var message = [
MessageStructure(messageType: 2, textsFrom: [“text1”, “text2”]),
MessageStructure(messageType: 2, textsFrom: [“text1”, “text2”]),
MessageStructure(messageType: 2, textsFrom: [“text1”, “text2”])
]
func changemessage(scores: Int) {
if scores == 1 {
self.message = [
MessageStructure(messageType: 2, textsFrom: [“text1”, “text2”]),
MessageStructure(messageType: 2, textsFrom: [“text1”, “text2”]),
MessageStructure(messageType: 2, textsFrom: [“text1”, “text2”])
]
}
else if scores == 2 {
self.message = [
MessageStructure(messageType: 2, textsFrom: [“text1”, “text2”]),
MessageStructure(messageType: 2, textsFrom: [“text1”, “text2”])
]
}
}
}
struct MessageStructure: Identifiable {
var id = UUID()
var messageType: Int
var textsFrom: [String]
}
struct MessagesView: View {
@State var showNavigation1: Bool = false
@StateObject var settings = GameSettings()
var Messages = MessageGetter()
var body: some View {
NavigationView {
List {
ForEach(0..<Messages.message.count) { section in
NavigationLink(destination: MessageDetailView(message: Messages.message[section])) {
MessagesRow(message: Messages.message[section])
}
}
}.navigationTitle("Messages")
.listStyle(PlainListStyle())
}
.environmentObject(settings)
.onAppear(perform: {Messages.changemessage(scores: settings.score)})
}
}