尝试创建新数组时出现编译错误

compilation error when trying to create a new array

你能帮我解决1个问题吗?我在尝试创建新数组时出错

错误文本: “不能在 属性 初始化程序中使用实例成员 'images';属性 初始化程序 运行 在 'self' 可用之前”

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

非常感谢

当您设置 class 时,每个 属性 都必须在 class 中不依赖于另一个 属性 进行初始化,因为直到整个事物已初始化,none 个属性可用。

你可以这样做:

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() ?? "")
]