Alain Stulz
Alain Stulz

Reputation: 744

Initialize multiple objects with names from array

I'm trying to create multiple instances of a structure in an elegant way.

I have an array with names:

let instanceNames = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]

and a structure to go along with that:

struct days {
var date = ""
var description = ""
var otherValue = ""
}

What I want to end up with is this:

var Monday = days()
var Tuesday = days()
var Wednesday = days()
var Thursday = days()
var Friday = days()

Is there a way to do this in one line, I tried this but of course it didn't work:

for day in instanceNames {
var day = days()
}

Any help would be appreciated much!

Upvotes: 0

Views: 154

Answers (4)

Alex Gaynor
Alex Gaynor

Reputation: 15009

No, there's no way to assign to many local variables in that way, your best bet would be to use a dictionary to do this:

var d = Dictionary<String, days>()
for day in instanceNames {
    d[day] = days()
}

Then you can address them with expressions like d["Monday"].

Upvotes: 1

Alain Stulz
Alain Stulz

Reputation: 744

I ended up doing this:

struct week {
var monday = day()
var tuesday = day()
var wednesday = day()
..
}

and

struct day {
var date = ""
var description = ""
..
}

Now I can initialize all those days with just one line of code:

currentWeek = week()

and objects for all days of a week are created. I can then access them via

currentWeek.monday

for example.

Thanks for the help!

Upvotes: 0

ldindu
ldindu

Reputation: 4380

Try the following, it might work for you.

let instanceNames = ["Monday", "Tuesday"]

struct days {
    var date: String
    var description: String
    var otherValue: String
}

for day in instanceNames{
    var day1 = days(date: day, description: "great", otherValue:"Awesome");
    println(day1.date)
}

Upvotes: 0

Maciej Oczko
Maciej Oczko

Reputation: 1225

You can't assign an instance to a day value. day is a string in your case. If you want to create instance per day, you can do the following:

struct Day {
    var date = ""
    var description = ""
    var otherValue = ""
}

var days : Day[] = []
for _ in instanceNames {
    var day = Day()
    days.append(day)
}

Upvotes: 2

Related Questions