In Java, any objects could be added to the List. It was very convenient to create a class with different fields (integers, strings, bitmaps, arrays, etc.), and then list the objects of this class. And you could quickly access any object in the list.

It was convenient for example when creating a news feed. I get information about the posts from the server. I post each post in a new object, where each type of information has its own field, for example, the name of the author of the post, the link to the avatar, the text of the post, etc. And I list objects. And if necessary, I refer to a particular object (post) and get the necessary information or change it.

I recently switched to swift and cannot find an alternative to a similar interface of collections there. Tell me if he is?

    3 answers 3

    If you just get and display, use Array for these purposes:

     var array = [NewsItem]() array.append(NewsItem(name, body, что-то еще)) 

    There are only 3 types in Swift: Array, Set and Dictionary, but they are much more powerful than in Java.

      What you are writing about is called a model. It is created as a subclass of the class NSObject . Here is an example of such a class:

      List.swift

       import UIKit class List: NSObject { let id: String? let username: String? // здесь могут быть Int, Array, Dictionary, свои классы, и т.д. init (dict: [:]) { self.id = dict["id"] self.username = dict["username"] super.init() } } 

      It is used later like this:

       let dict = ["id":"1234", "username":"Name"] let list = List(dict: dict) print(list.id) print(list.username) 

      Alternatively, you can opt out of the init method and assign the values ​​directly (then the let should be replaced with var).

        I think for the problem with the news feed, you are best to use CoreData. Create a model, generate classes for it, and then create the object you need, requesting it from the model with the necessary parameters. Here is a good lesson on CoreData for new items. Well, or if you really want to use the collection, you can create an array with the data type you need: let myArray = [News]() , where News class of the object whose instance you want to create. You can also use AnyObject for objects of any type, but Swift is a strictly typed language and when retrieving an object, you need to specify its type. Alternatively, you can create a dictionary: let dic = [String:AnyObject]() , where the key is always a string, and the value can be of any type, but again you must cast the value to the desired type to use it.