Swift: Create Array of Dictionary Values

14,135

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")
}
Share:
14,135
Admin
Author by

Admin

Updated on June 06, 2022

Comments

  • Admin
    Admin almost 2 years

    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.

  • Nate Cook
    Nate Cook over 9 years
    The result is optional - you can use a ! to force unwrap if you're sure the key is valid, or use optional binding or a nil coalescing operator to unwrap it if you aren't. (Answer now shows force unwrapping.)