Swift: create an array of dictionary values
I am very new to Swift. I have a table view controller in which I have stated the following:
var parts = [String:[String]]() //Key: String, Value: Array of Strings
var partsSectionTitles = [String]()
In my viewDidLoad function, I have:
parts = [
"Part 1" : ["1", "2", "3"],
"Part 2" : ["1", "2"],
"Part 3" : ["1"]
]
//Create an array of the keys in the parts dictionary
partsSectionTitles = [String](parts.keys)
In my cellForRowAtIndexPath function, I have:
let cell = tableView.dequeueReusableCellWithIdentifier("TableCell", forIndexPath: indexPath) as UITableViewCell
var sectionTitle: String = partsSectionTitles[indexPath.section]
var secTitles = parts.values.array[sectionTitle]
cell.textLabel.text = secTitles[indexPath.row]
I am trying to create an array secTitles consisting of values ββfrom a dictionary of details corresponding to the keys, sectionTitle. However, I got this error message:
'String' does not convert to 'Int'
I was able to do this in Objective-C:
NSString *sectionTitle = [partsSectionTitles objectAtIndex:indexPath.section];
NSArray *secTitles = [parts objectForKey:sectionTitle];
Also, I would like to know if I can add / remove values ββin arrays and dictionaries afterwards. In other words, are they mutable? I read several articles that say that Swift arrays and dictionaries are not actually mutable. I just wanted to know if anyone can confirm this. Thank you in advance for your answers.
You just don't need values.array
:
var chapterTitles = partsOfNovel[sectionTitle]!
Arrays inside dictionaries can be changed if the dictionary itself is changed, but you need to assign via the expand operator:
if partsOfNovel[sectionTitle] != nil {
partsOfNovel[sectionTitle]!.append("foo")
}
source to share