[英]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: 我可以使用下一个代码在C#中使用一些对象类型轻松定义新集合:
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? 上面代码列表的Swift编程语言的模拟是什么?
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
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.