简体   繁体   English

在自己的内部创建类的实例

[英]Create an instance of a class inside its own self

Here's the situation. 这是情况。 I have a swift model class file that contains all the variables for a weather forecast (min temperature, max temperature, humidity, etc). 我有一个快速的模型类文件,其中包含天气预报的所有变量(最低温度,最高温度,湿度等)。 The class also contains the function that downloads all the data from the API. 该类还包含从API下载所有数据的函数。 My question is, is it possible to create an array of the class inside the class itself, so that I can append a number of objects (of the same class itself) based on the number of days of forecast the API sends back? 我的问题是,是否可以在类本身内部创建类的数组,以便根据API发送回的预测天数追加一些对象(同一类本身)? If so, can you tell me how it could be achieved? 如果是这样,您能告诉我如何实现吗? The other option I have that totally works, is to do the API downloading and parsing outside of the forecast class (in the ViewController) but that would make my ViewController messy. 我完全可以使用的另一个选项是在预测类之外(在ViewController中)进行API下载和解析,但这会使我的ViewController混乱。

There's nothing preventing you from referencing a class name within its definition. 没有什么可以阻止您在其定义中引用类名。 So you can do something like this: 因此,您可以执行以下操作:

class Foo {
    var boz = [Foo]() // you can append to this array as needed
}

You shouldn't call the API to get all the weather's datas in your model but in a dedicated class. 您不应该调用API来获取模型中所有天气数据,而应使用专门的类。 Also, you shouldn't parse and store the datas inside your model. 另外,您不应该在模型内部解析和存储数据。

In your model, you only need to have all the attributes of your object and methods. 在模型中,您只需要具有对象和方法的所有属性。

Maybe you can create an Helper class where you implements all this methods and store the datas. 也许您可以创建一个Helper类,在其中实现所有这些方法并存储数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM