Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
158 views
Welcome To Ask or Share your Answers For Others

1 Answer

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...