我可以使用下一个代码轻松定义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" }
};
上面的代码列表中Swift编程语言的模拟是什么?
答案 0 :(得分:1)
近似的等价物是:
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 :(得分:0)
如果使用结构,代码非常相似:
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"),
]
如果你想要一个类而不是一个结构(通常,你可能想先考虑一个结构,只有当你真的需要这个类带来的类时),那么你还需要一个初始化器:
public class Person {
public var id: Int
public var name: String
public init(id: Int, name: String) {
self.id = id
self.name = name
}
}