Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
160 views
in Technique[技术] by (71.8m points)

Auto add a class instance to an array in Swift

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

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

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...