问题
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] ...]
so that the loop equals :
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])
Example for adressing:
print(guests[0].age)
>>>1
I've searched a lot but am getting directed to issues regarding creating variables in classes.
Thank you very much!
回答1:
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))
}
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) }
EDIT: 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
}
回答2:
//MARK: Call method to create multiple instances
createInstance([("Ann", 1), ("Bob", 2)])
func createInstance(_ input: Array<Guest>) {
for each in input {
guests.append(Guest(name: each.0, age: each.1))
}
}
来源:https://stackoverflow.com/questions/45989491/create-objects-instances-in-variables-swift