How do I define a new generic list of objects in Swift?

I can easily define a new collection with some object type in C # using the following code:

class Person
{
    public int Id { get; set; }
    public string Name { get; set; }

}

// in some other method
var listPesrons = new List<Person>
{
    new Person { Id = 0, Name = "Oleg" },
    new Person { Id = 1, Name = "Lena" }
};

      

What is analog for the Swift programming language for the code list above?

+3


source to share


2 answers


A close equivalent would be:



public class Person {
    public var id: Int
    public var name: String

    public init(id: Int, name: String) {
        self.id = id
        self.name = name
    }
}

var listPersons = [
    Person(id: 0, name: "Oleg"),
    Person(id: 1, name: "Lena")
]

      

+1


source


When using structure, the code is very similar:

public struct Person {
    public var id: Int
    public var name: String
}

// persons will be an Swift Array 
let persons = [
    Person(id: 0, name: "Oleg"),
    Person(id: 1, name: "Lena"),
]

      



If you want a class instead of a struct (and generally you can think of a struct first, and a class only if you really need function classes), you also need an initializer:

public class Person {
    public var id: Int
    public var name: String

    public init(id: Int, name: String) {
        self.id = id
        self.name = name
    }
}

      

0


source







All Articles