0

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

1
  • You need to declare your var as lazy. lazy var section: [StudentModel] = [StudentModel(name: names.randomElement() ?? "", image: images.randomElement() ?? "")] Commented Jan 16, 2022 at 5:27

1 Answer 1

2

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() ?? "")
]
Sign up to request clarification or add additional context in comments.

1 Comment

I wonder how this solution gets 2 votes up

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.