Search code examples
arraysswiftswiftuiswift3swiftui-list

compilation error when trying to create a new array


Can you help me with 1 question please? I have erorr while try to create new array

Error text: "Cannot use instance member 'images' within property initializer; property initializers run before 'self' is available"

class ViewModel: ObservableObject {
    
    @Published var students: [StudentModel] = [
    StudentModel(name: "Roman", image: "bolt.fill"),
    StudentModel(name: "Ivan", image: "leaf.circle.fill"),
    StudentModel(name: "Denis", image: "ant.fill"),
    StudentModel(name: "Pavel", image: "pawprint.fill")
    ]
    
    @Published var names = ["Kirill","Mark","Vladimir","Andrew","Maksim","Igor","Petr", "Alexey"]
    
    @Published var images = ["bolt.fill", "leaf.circle.fill", "ant.fill", "pawprint.fill", "airtag.fill", "infinity.circle.fill"]
    
    var section: [StudentModel] = [StudentModel(name: names.randomElement() ?? "", image: images.randomElement() ?? "")]
    
    
    func addRow() {
        students.append(StudentModel(name: names.randomElement() ?? "", image: images.randomElement() ?? "" ))
        }

Thank you very much


Solution

  • When you are setting up your class, each property has to be initialized without a dependency on another property in that class., because until the whole thing is initialized, none of the properties are available yet.

    You could do something like this:

    var section: [StudentModel] = [
        StudentModel(
                    name: ["Kirill","Mark","Vladimir","Andrew","Maksim","Igor","Petr", "Alexey"].randomElement() ?? "",
                    image: ["bolt.fill", "leaf.circle.fill", "ant.fill", "pawprint.fill", "airtag.fill", "infinity.circle.fill"].randomElement() ?? "")
    ]