简体   繁体   中英

How can I define new generic list of objects in Swift?

I can easy define new collection with some object type in C#, using the next 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 the analog for Swift programming language for the code list above?

The 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")
]

If using a struct, 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 wanted a class instead of a struct (and generally, you might want to think about a struct first, and a class only if you really need the features classes bring) then you'll 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
    }
}

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