简体   繁体   中英

How can I add Items to an array of a class type, dynamically in Swift

I have a code snippet similar to this

class Student{
var id: Int
var name: String
var mark: Int
}

class Fetch{
init(count:Int){
   var student=[Student]()
}}

I want to add details of students(id, name and mark) of 'count' number of students

in playground

struct Student{
    var id: Int
    var name: String
    var mark: Int
    
    init(id: Int, name: String, mark: Int) {
        self.id = id
        self.name = name
        self.mark = mark
    }
}

class Fetch{
    var students = [Student]()
    
    init(count:Int){
        students = []
        for i in 0..<count {
            let s = Student(id: i + 1, name: "Student\(i+1)", mark: (i % 5) + 1)
            students.append(s)
        }
    }
}

let sc = Fetch(count: 4)
print(sc.students)

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM