简体   繁体   中英

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. 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? 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.

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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