Auto add a class instance to an array in Swift

2020-01-19 03:18发布

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!

3条回答
老娘就宠你
2楼-- · 2020-01-19 04:04

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)
    }
}
查看更多
forever°为你锁心
3楼-- · 2020-01-19 04:16

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)
查看更多
狗以群分
4楼-- · 2020-01-19 04:17

Have you tried products.append(self) ?

查看更多
登录 后发表回答