I'm fairly new to Swift, so be gentle...
I have a class, called ProgramOptions, as so:
class ProgramOptions {
var startDate: Date = Date()
var trackedActivities = [TrackedItem]()
var trackedFoods = [TrackedItem]()
var trackedDrugs = [TrackedItem]()
...
}
TrackedItem is another class of mine.
In a TableViewController's code I want to select one of the arrays from an instance of ProgramOptions, based on what section of the table is in question. I want to then do many possible things, like remove or add items, edit them, etc.
Being a Swift beginner, I naively wrote this function:
func trackedArrayForSection(_ section: Int) -> [TrackedItem]? {
switch(section) {
case 1: return programOptions.trackedActivities
case 2: return programOptions.trackedFoods
case 3: return programOptions.trackedDrugs
default: return nil
}
}
(Section 0 and Sections > 3 don't have associated arrays so I return nil)
But then harsh reality bit me. I guess the array is a copy. (Or my weak understanding of similar question on StackOverflow indicates that it is sometimes copied.)
So here's the question for you... How could I write my trackedArrayForSection so that I get a reference to actual array sitting in ProgramOptions that I can then add and remove items from?
I could, of course, have a switch statement every place I use this, but there are close to a zillion of them and I'd like to avoid that. I'm assuming there is an easy answer to this and I'm just too ignorant at this point to know it.
Thanks for your help!
One possibility is to create a wrapper class to store the array of TrackedItems. Say, for example:
class TrackedItemCollection {
var items = Array<TrackedItem>()
}
and then in your implementation:
class ProgramOptions {
var startDate: Date = Date()
var trackedActivities = TrackedItemCollection()
var trackedFoods = TrackedItemCollection()
var trackedDrugs = TrackedItemCollection()
...
}
func trackedCollectionForSection(_ section: Int) -> TrackedItemCollection? {
switch(section) {
case 1: return programOptions.trackedActivities
case 2: return programOptions.trackedFoods
case 3: return programOptions.trackedDrugs
default: return nil
}
}
When you want the array, you use the items property in TrackedItemCollection. As TrackedItemCollection is a class and thus a reference type, you won't have the arrays copyed.
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