快速创建对象/实例 [英] create objects/instances in variables swift
问题描述
我不知道在Swift中创建实例或处理实例时如何使用变量: 例如,如何在循环中执行以下操作(创建实例):
I don't know how to use variables when creating Instances or adressing them in Swift: For exmaple how do I do following in a loop (creating Instances):
class Guest {
let name: String
var age: Int
init(name: String, age: Int) {
self.name = name
self.age = age
}
}
let guests = [["ann", 1] , ["bob", 2] ...]
使循环等于:
let ann = Guest(name: "ann" , age: 1)
let bob = Guest(name: "bob" , age: 2)
...
我正在寻找这样的东西:
edit: I am looking for something like this:
for i in guests {
let i[0] = Guest(name: i[0] , age: i[1])
地址示例:
print(guests[0].age)
>>>1
我进行了很多搜索,但直接针对在类中创建变量的问题.
I've searched a lot but am getting directed to issues regarding creating variables in classes.
非常感谢!
推荐答案
您可以使用经典循环来做到这一点:
You can do that with a classic loop:
let input = [("Ann", 1), ("Bob", 2)]
var guests: [Guest] = []
for each in input {
guests.append(Guest(name: each.0, age: each.1))
}
但是,使用功能性技术可以更简洁(并且避免使用var
)完成此操作:
However, it can be done more concisely (and with avoidance of var
) using functional techniques:
let guests = [("Ann", 1), ("Bob", 2)].map { Guest(name: $0.0, age: $0.1) }
基于字典的解决方案(Swift 4;对于Swift 3版本,只需使用经典循环即可)
Dictionary-based solution (Swift 4; for Swift 3 version just use the classic loop)
let input = [("Ann", 1), ("Bob", 2)]
let guests = Dictionary(uniqueKeysWithValues: input.map {
($0.0, Guest(name: $0.0, age: $0.1))
})
或者,如果两个客人的名字可能相同:
Or, if it's possible for two guests to have the same name:
let guests = Dictionary(input.map { ($0.0, Guest(name: $0.0, age: $0.1)) }) { first, second in
// put code here to choose which of two conflicting guests to return
return first
}
有了字典,您可以执行以下操作:
With the dictionary, you can just do:
if let annsAge = guests["Ann"]?.age {
// do something with the value
}
这篇关于快速创建对象/实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!