Reputation: 496
I have a popover view controller that contains a table view with a list of options, similar to a drop down selection list. This table view is populated dynamically, depending on which "select" button the user hits on the parent view controller. I have several Arrays built for the various option sets to populate the TVC. How can I use the fieldIndex dictionary to automatically set the array to be used as the TVC datasource for the popover?
class MyWidget : NSObject {
var fieldIndex : [Int:String] = [
0 : "make",
1 : "model",
2 : "year"
]
var make = String()
var model = String()
var year = String()
}
var makes = ["Acme", "Contoso", "Tradewinds"]
var models = ["Model1", "Model2", "Model3"]
var years = ["2015", "2016", "2017"]
Upvotes: 0
Views: 380
Reputation: 9226
You can simply create dictionary of type Int: [String]
class MyWidget : NSObject {
// empty fieldData dictionary of type Int: [String]
var fieldData = [Int: [String]]()
}
// add data like this
fieldData[0] = ["Acme", "Contoso", "Tradewinds"]
fieldData[1] = ["Model1", "Model2", "Model3"]
fieldData[2] = ["2015", "2016", "2017"]
// get data like this
let makeArray = fieldData[0]
Upvotes: 1
Reputation: 4795
An alternative to using NSObject
is to add this logic into a function
directly in your code:
func getArray(_ positionInDictionary: Int) -> [String]{
var fieldData: [Int:[String]] = [0 : ["Choice 01", "Choice 02", "Choice 03"], 1 : ["Choice 11","Choice 12","Choice 13"]]
if let str = fieldData[positionInDictionary]{
return str
}
else{ return []}
}
Usage:
var dataArray = getArray(1)
Also, this is IMO the simplest and fastest solution, and you can retrieve your dictionary from wherever you want.
Upvotes: 0
Reputation: 21013
I might approach it this way.
enum Attribute {
case make, model, year
var name: String {
switch self {
case .make: return "Make"
case .model: return "Model"
case .year: return "Year"
}
}
var allAttribtues: [Attribute] {
return [.make, .model, .year]
}
}
class AttributeDataSource {
func options(for attribute: Attribute) -> [String] {
switch attribute {
case .make: return ["Acme", "Contoso", "Tradewinds"]
case .model: return ["Model1", "Model2", "Model3"]
case .year: return ["2015", "2016", "2017"]
}
}
}
let dataSource = AttributeDataSource()
dataSource.options(for: .make) // -> ["Acme", "Contoso", "Tradewinds"]
dataSource.options(for: .model) // -> ["Model1", "Model2", "Model3"]
dataSource.options(for: .year) // -> ["2015", "2016", "2017"]
Don't hesitate to make first-class models for your data structures. Most of the time it will make things much more clear.
Upvotes: 0