20

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.

4 Answers 4

31

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

heroes.append(contentsOf:[abaddon, ember, gondor])
Sign up to request clarification or add additional context in comments.

Comments

7

I try like this:

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

So I don't need to declare all objects

3 Comments

This is smart. You declare the array of names first, then create an array that contains one new instance of Hero for each name on the list.
If the initializer ever requires more than just a single argument, this will get very messy.
Yes, if Hero object has more properties, this solution is not convenient anymore.
2

Swift 4.x answer of @TPlet

nameField.append(contentsOf: [abaddon, ember, gondor])

Comments

1

Why not just

var heroes = [abaddon, ember, ..., wind]

3 Comments

Because he needs objects of type Hero, that likely hold other additional properties/state besides name; and array of strings won't do.
They aren't strings (no quotes around them), they are the actual variable names.
My bad, missed that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.