Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append object multiple time to an array

Tags:

swift

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.

like image 211
Khuong Avatar asked Mar 31 '16 06:03

Khuong


People also ask

How do you add the same element multiple times in an array?

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.

How do you repeat values in an 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.

What is time complexity of appending an element to an array?

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 .


2 Answers

If you want to append multiple objects, You could wrap them into an array themselves and use appendContentsOf.

heroes.append(contentsOf:[abaddon, ember, gondor])
like image 70
TPlet Avatar answered Sep 27 '22 19:09

TPlet


I try like this:

let heroes = ["abaddon","ember","gondar",etc].map { Hero(name: $0) } 

So I don't need to declare all objects

like image 32
Khuong Avatar answered Sep 27 '22 18:09

Khuong