yama_HD
yama_HD

Reputation: 568

Swift - Cannot append Object to Array

I have created a New View in my App, but the Identifiable Object won't append to the Array. I really don't know why its not appending...

Here is the Code:

struct FirstSettingsIdentifiables: Identifiable {
    var id: UUID = UUID()
    
    var name: String
    var icon: String
}
struct SettingsView: View {
    
    @EnvironmentObject var settingItems: ContentModel
    
    @State var firstArr: [FirstSettingsIdentifiables] = []
    
    init() {
        createFirstList()
        print("Settings successfully initialized.")
    }
    
    var body: some View {
        
        return VStack {
            Text("Einstellungen")
                .font(.title)
            
            NavigationView {
                //Mitteilungen Liste
                List(firstArr) { x in
//                    ForEach(firstArr) { x in
    //                    VStack {
    //                        Image(systemName: x.icon)
                            Text("Das ist ein test")
    //                    }
//                    }
                }.navigationBarTitle("Mitteilungen")
            }
        }
    }
    
    func createFirstList() {
        
        let aText = "Mitteilungen"
        let aIcon = "info.circle.fill"
        let aObject = FirstSettingsIdentifiables(name: aText, icon: aIcon)
        
        firstArr.append(aObject)
        
        print(firstArr.count)
        
    }
    
    
}

The problem is probably in the createFirstList() Section. In this function, the Object aObject is full of data(This is working fine), but then the Object won't append to my firstArr. The count is always 0.

What am I doing wrong here?

Upvotes: 0

Views: 294

Answers (1)

George
George

Reputation: 30341

You are changing the value of firstArr too early. Instead of calling createFirstList() in the init, remove that and instead add the following code onto the view body:

VStack {
    /* ... */
}
.onAppear(perform: createFirstList)

Alternatively, you could do the following:

init() {
    _firstArr = State(initialValue: getFirstList())
    print(firstArr.count)
    print("Settings successfully initialized.")
}

/* ... */

func getFirstList() -> [FirstSettingsIdentifiables] {
    let aText = "Mitteilungen"
    let aIcon = "info.circle.fill"
    let aObject = FirstSettingsIdentifiables(name: aText, icon: aIcon)
    return [aObject]
}

Upvotes: 2

Related Questions