I want to append all of my object in a single line. I have some object like this:
let abaddon = Hero(name: "abaddon")
let ember = Hero(name: "ember")
let gondar = Hero(name: "gondar")
let kael = Hero(name: "kael")
let kunkka = Hero(name: "kunkka")
let layana = Hero(name: "layana")
let lucifer = Hero(name: "lucifer")
let omni = Hero(name: "omni")
let soul = Hero(name: "soul")
let wind = Hero(name: "wind")
The Hero Object like so:
class Hero {
var name: String!
var image: UIImage? {
return UIImage(named: "\(name)")!
}
required init(name: String) {
self.name = name
}
}
And I want to put them to this array: var heroes = [Hero]()
But I see append
only be able to put one object each time.
heroes.append(abaddon)
How to append multiple objects in single line, something like this:
heroes.append([abaddon, ember, gondar])
Any helps would be appreciated, thanks.
We can use the for loop to run the push method to add an item to an array multiple times. We create the fillArray function that has the value and len parameters. value is the value we want to fill in the array. len is the length of the returned array.
The repeat() function is used to repeat elements of an array. Input array. The number of repetitions for each element. repeats is broadcasted to fit the shape of the given axis.
In case of static list/array the time complexity must be O(n), but in case of dynamic array/list, the time complexity comes O(1) because in dynamic array there is a facility to allocate extra memory for the append operation .
If you want to append multiple objects, You could wrap them into an array themselves and use appendContentsOf.
heroes.append(contentsOf:[abaddon, ember, gondor])
I try like this:
let heroes = ["abaddon","ember","gondar",etc].map { Hero(name: $0) }
So I don't need to declare all objects
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With