0

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!

4 Answers 4

2

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)
}
Sign up to request clarification or add additional context in comments.

Comments

1

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"].

1 Comment

Thanks, bit of a pity that there is no really simple way to do this but it'll work.
0

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)
}

Comments

0

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!

Comments

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.