自动将类实例添加到Swift中的数组 [英] Auto add a class instance to an array in Swift

查看:60
本文介绍了自动将类实例添加到Swift中的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将新的类实例自动添加到数组?

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

示例:

class Product {
    var name: String?
}

var products = [Product]()

如何将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.

我尝试过这样的事情:

class Product {
    var name: String?

    init() {
        products.append(Produt)
    }

    var products = [Product]()

谢谢!

推荐答案

如果您希望将新创建的对象存储在 products 数组中,则需要将其声明为 static 属性,以便共享

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)
    } 
}

现在使用 Product.products 产品数组c>。

Now use this products array using Product.products.

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

这篇关于自动将类实例添加到Swift中的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆