Auto add a class instance to an array in Swift

2020-01-19 03:45发布

问题:

How can I auto add a new class instance to an array?

Example:

class Product {
    var name: String?
}

var products = [Product]()

How can I add a new instance of a Product class to the products Array? How can I append to the array?

I tried some code but I don't know how to reference the class in own class.

I tried something like this:

class Product {
    var name: String?

    init() {
        products.append(Produt)
    }

    var products = [Product]()

Thanks!

回答1:

If you want your newly created object stored in products array then you need to declare it as static property so that it is shared by all instance otherwise it will just add first object for your every instance.

class Product {
    var name: String?
    static var products = [Product]()

    init() {
        Product.products.append(self)
    }

    init(name: String) {
        self.name = name
        Product.products.append(self)
    } 
}

Now use this products array using Product.products.

_ = Product(name: "One")
_ = Product(name: "two")
print(Product.products)


回答2:

I dont't know why you need it, but you can use

class Product {
    static var products: [Product] = []

    var name: String?

    init() {
        products.append(self)
    }
}


回答3:

Have you tried products.append(self) ?