Reputation:
I am very new to Swift. I have a table view controller in which I have declared 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 the values from the parts dictionary that correspond to the keys, sectionTitle. However, I received this error message:
'String' is not convertible to 'Int'
I was able to do it in Objective-C:
NSString *sectionTitle = [partsSectionTitles objectAtIndex:indexPath.section];
NSArray *secTitles = [parts objectForKey:sectionTitle];
Also, I would like to know if I will be able to add/remove the the values in the arrays and dictionaries later on. In other words, are they mutable? I've read a few articles that say Swift arrays and dictionaries aren't actually mutable. I just wanted to know if anyone could confirm that. Thank you in advance for your responses.
Upvotes: 4
Views: 14233
Reputation: 93276
You just don't need the values.array
:
var chapterTitles = partsOfNovel[sectionTitle]!
Arrays inside dictionaries can be mutated as long as the dictionary itself is mutable, but you'll need to assign through an unwrapping operator:
if partsOfNovel[sectionTitle] != nil {
partsOfNovel[sectionTitle]!.append("foo")
}
Upvotes: 3